本文介绍了是否可以模拟从golang中的包导入的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下测试方法,它使用从包中导入的函数。
import xyz
func abc(){
...
v:= z.SomeFunc()
...
}
是否可以在golang中模拟 SomeFunc()
?
解决方案
是的,只需简单的重构。创建一个函数类型的 zSomeFunc
变量,用 z.SomeFunc
初始化,并且调用你的包而不是 z.SomeFunc()
:
var zSomeFunc = z.SomeFunc
func abc(){
// ...
v:= zSomeFunc()
// ...
}
$ c在测试中,你可以为 zSomeFunc
分配另一个函数,一个在测试中定义的函数,并做任何测试想要它。
例如:
func TestAbc(t * testing.T){
//保存当前函数并在最后恢复:
old:= zSomeFunc
defer func(){zSomeFunc = old}()
zSomeFunc = func()int {
//这将会被调用,做任何你想做的事
//返回你想要的任何
return 1
}
//调用测试函数
abc()
//检查预期行为
}
查看相关/可能的重复:
I have the following method to test, which uses a function imported from a package.
import x.y.z
func abc() {
...
v := z.SomeFunc()
...
}
Is it possible to mock SomeFunc()
in golang?
解决方案 Yes, with a simple refactoring. Create a zSomeFunc
variable of function type, initialized with z.SomeFunc
, and have your package call that instead of z.SomeFunc()
:
var zSomeFunc = z.SomeFunc
func abc() {
// ...
v := zSomeFunc()
// ...
}
In tests you may assign another function to zSomeFunc
, one that is defined in tests, and does whatever the test wants it to.
For example:
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
}
See related / possible duplicate:Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)
这篇关于是否可以模拟从golang中的包导入的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!