unit-testing - 如何使用相互依赖的接口(interface)方法模拟结构

标签 unit-testing go testing mocking go-interface

我在 Go 中为一个相当常见的用例/模式编写单元测试时遇到了麻烦。

想象一下,如果你愿意的话,是这样的:

package main

type Resource struct {
    name string
}

type ResourceManager interface {
    GetResource(id string) (*Resource, error)
    GetAllResources() ([]*Resource, error)
}

type ResourceManagerImpl struct {
}

func (r *ResourceManagerImpl) GetResource(id string) (*Resource, error) {
    resource := &Resource{}
    var err error

    // fetch resource.
    // ...

    return resource,  err
}

func (r *ResourceManagerImpl) GetAllResources() ([]*Resource, error) {
    var resources []*Resource
    var err error

    // for _, id := range ids {
    //  resource = r.GetResource(id)
    //  resources = append(resources, resource)
    // }

    return resources, err
}
GetAllResources 是一种常见的模式。调用 GetResource根据需要反复。

我可以使用 gomocktestify测试 GetResource 的所有排列.但是,在测试时 GetAllResource , 我想模拟 GetResource .否则,测试将成为一场噩梦。这就是在 easymock 中的做法或 mockito在 Java 使用部分模拟的情况下。但是,尚不清楚如何在 Golang 中实现相同的目标。

具体来说,我找不到如何部分模拟 struct .大多数建议都围绕着打破这样的struct s 但在这种情况下,struct已经是最低限度了。不要破坏 ResourceManager 似乎是一个公平的要求。接口(interface)(单和多)以进行测试,因为这没有多大意义,而且充其量是笨拙的,并且随着更多此类方法进入接口(interface),也无法很好地扩展。

最佳答案

这就是我处理这种情况的方式:

func (r *ResourceManagerImpl) GetAllResources() ([]*Resource, error) {
   return getAllResources(r)
}


func getAllResources(r ResourceManager) ([]*Resource,error) {
  ...
}

然后你测试getAllResources而不是 GetAllResources带有 mock 的r .如果您遇到GetAllResources从代码中调用,你必须模拟 GetAllResources , 你可以做:
var getAllResources=func(r ResourceManager) ([]*Resource,error) {
...
}

并将 getAllResources 分配给一个测试实例。

关于unit-testing - 如何使用相互依赖的接口(interface)方法模拟结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313552/

相关文章:

php - 在 Laravel 4 单元测试中,如何在请求中设置 cookie?

go - 如何打印通过标准输入引入的行数?

ruby-on-rails - 嵌套资源的 Controller 测试

testing - 在 Jira 中使用不同的用户和指标来解决和关闭问题

c++ - 单元测试扫描

java - 存储库模拟不起作用。返回错误的 Http 状态

go - 在 goroutines 中启动 goroutines 是否可以接受?

python - python测试中的函数调用列表

unit-testing - 没有断言的单元测试

http - 如何在golang中缓存http.Response?