是的,只需进行简单的重构即可。创建一个
zSomeFunc函数类型的变量,用初始化
z.SomeFunc,并让您的包调用而不是
z.SomeFunc():
var zSomeFunc = z.SomeFuncfunc 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}


