unit-testing - 戈朗 : Replace function unit testing

标签 unit-testing go mocking

我正在使用 Golang,目前我正在用 Testify 做一些有趣的单元测试,我的文件看起来像这样

type myStruct struct {
  field_1 string

}
func (self *myStruct) writeFirst()  {
//doing something
//modify field_1
self.writeSecond()
}

func (self *myStruct) writeSecond() {
//doing something
}

在这种情况下,我正在测试 writeFirst(),但我正在尝试替换 writeSecond(),因为它使用了我不想使用的 http 内容,因为它可以访问互联网。

我认为使用第二个结构并将 myStruct 设置为匿名字段将是解决方案,但它不起作用,因为我的第二个结构和 myStruct 具有不同的上下文。

在这种情况下,我不能使用模拟,因为 writeSecond 是结构的一个方法。

我的测试用例是这样的:

func TestWriteFirst(t *testing.T) {
   myStc := myStruct{}
   assert.Equal(t,"My response", myStc.field_1)
}

我想要的只是测试 writeFirst 而不传递给 writeSecond()

最佳答案

为了说明 Not-a-Golfer 提到的那种重构在 the comments ,您可以考虑仅在作为接口(interface)的实例上调用第二个函数:

type F2er interface {
    Func2()
}

type S struct{ _f2 F2er }

var s = &S{}

func (s *S) f2() F2er {
    if s._f2 == nil {
        return s
    }
    return s._f2
}

func (s *S) Func1() {
    fmt.Println("s.Func1")
    s.f2().Func2()
}

此处:Func1s.f2() 上调用 Func2,而不是直接在 s 上调用。

  • 如果 s 中没有任何设置,s.f2() 返回...本身:s
  • 如果 s._f2 被任何其他实现 Func2struct 替换,s.f2()返回该实例而不是它本身。

请参阅此 playground script 中的完整示例.

输出:

TestFunc1
s.Func1
s.Func2

TestFunc1bis
s.Func1
testS.Func2    <=== different Func2 call

关于unit-testing - 戈朗 : Replace function unit testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791040/

相关文章:

sockets - 限制连接到网络服务的客户端数量

unit-testing - 单元测试 DAO 时使用模拟对象的策略

web - 在 Web 浏览器中模拟 GPS 定位路线

unit-testing - 如果您已经进行了功能测试,还需要进行单元和集成测试吗?

c# - 为 HttpContext.Current.Session 编写单元测试时出现问题

json - 无法使用 Golang 从 App Engine 将有效的 JSON 数据成功发布到远程 URL

google-app-engine - 如何使 App Engine HTTP URL 处理程序只能在内部调用?

c# - 在 C# 单元测试中向模拟数据库添加数据的方法

python - 我可以使用部分实现来建立测试期望吗?

java - Java 中是否有框架来设置持久层?