我正在使用 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()
}
此处:Func1
在 s.f2()
上调用 Func2
,而不是直接在 s
上调用。
- 如果
s
中没有任何设置,s.f2()
返回...本身:s
- 如果
s._f2
被任何其他实现Func2
的struct
替换,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/