我有以下方法要测试,它使用从包中导入的函数.
import x.y.z
func abc() {
...
v := z.SomeFunc()
...
}
可以在golang 模拟SomeFunc()
吗?
我有以下方法要测试,它使用从包中导入的函数.
import x.y.z
func abc() {
...
v := z.SomeFunc()
...
}
可以在golang 模拟SomeFunc()
吗?
是的,只需简单的重构.创建一个函数类型为zSomeFunc
的变量,初始化为z.SomeFunc
,并让您的包调用该变量,而不是z.SomeFunc()
:
var zSomeFunc = z.SomeFunc
func abc() {
// ...
v := zSomeFunc()
// ...
}
在测试中,您可以将另一个函数赋给zSomeFunc
,该函数是在测试中定义的,并且可以执行测试希望它执行的任何操作.
例如:
func TestAbc(t *testing.T) {
// Save current function and restore at the end:
old := zSomeFunc
defer func() { zSomeFunc = old }()
zSomeFunc = func() int {
// This will be called, do whatever you want to,
// return whatever you want to
return 1
}
// Call the tested function
abc()
// Check expected behavior
}
请参阅相关/可能的复制: Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)个