我有以下方法来测试,它使用从包中导入的函数。
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)
关于unit-testing - 是否可以模拟从 golang 中的包导入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42952191/