【问题标题】:Mocking an external Library for unit test模拟外部库进行单元测试
【发布时间】:2020-01-03 13:03:54
【问题描述】:

我有一个下面的函数 tryGet() 来进行单元测试:

type config struct {
    Key      string        `json:"key"`
    Client   todo.Client  `json:"client"`
}

var instance *config

func (c *config) tryGet() error {
    client := &http.Client{}
    tClient := Client{"http://url", client}
    configValues := config{"Key", tClient} 
    Instance := &configValues
    err := Instance.Client.perform("GET", header)
    return nil
}

// 名为“todo”的包中的外部库具有以下结构和函数

package todo
type Client struct {
    BaseURL         string
    HTTPClient      *http.Client
}

func (client *Client) perform() error {

    return nil
}

我发现很难模拟客户端并在外部包 todo 中执行

【问题讨论】:

  • 只执行返回 nil 吗?
  • @edkeveked 否。它做了一些操作,如果成功则返回 nil else error
  • 您能否在您的问题中添加您在代码中的调用方式?
  • @edkeveked 我已经更新了关于如何调用 perform 的代码

标签: go mocking


【解决方案1】:

如果外部库不受您的控制(我假设是这种情况),那么您应该假设其中的代码已经过测试,因此您应该在您可以控制代码的点创建边界。

为此,您应该在配置结构边界处创建接口。

type ClientInterface interface {
    perform() error
}

type config struct {
    Url      string            `json:"url"`
    Client   ClientInterface   `json:"client"`
}

var instance *config

func (c *config) tryGet() error {
    err := c.Client.perform("GET", header)
    return nil
}

通过这种方式,您不必关心测试较低级别的代码库,您只关心此模块是否具有执行功能以及在特定条件下您的代码是否正确运行。

然后您可以创建一个模拟 todo.Cient 结构,您可以用它替换正常的结构并让它返回各种事物和行为来测试您的代码。

【讨论】:

    【解决方案2】:

    你可以按如下方式模拟函数

    type myImpl todo.Client 
    
    func (client *myImpl) perform() error {
        // do what you want to assert in the test
        return nil
    }
    

    然后,当你必须使用 todo.Client 时,你将使用 myImpl

    如果您正在使用带有 todo.Client 类型参数的函数,则如果您传递 myImpl 类型的参数,它将无法工作。会报错:

    不能在字段值中使用客户端(类型 myImpl)作为类型 todo.Client

    为了解决这个问题,可以创建一个接口

    type Client interface {
        perform() error
    }
    

    现在类型 Client 应该替换要单元测试的函数的类型 todo.Client。

    type config struct {
        Url      string        `json:"url"`
        Client   Client        `json:"client"`
    }
    

    通过此更改,提供接口myImpl 的实现Client 的上述代码应该可以工作

    【讨论】:

    • 当我像你说的那样模拟时出现以下错误:不能在字段值中使用客户端(类型 myImpl)作为类型 todo.Client
    • 上述更改删除了类型错误,但显示了一个编译错误接口在我的库文件中包含类型客户端接口 { todo.Client } 的嵌入非接口
    • 你可以用perform() error创建界面
    猜你喜欢
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2013-11-12
    • 2018-11-21
    • 2018-10-19
    • 2013-07-24
    相关资源
    最近更新 更多