我在 go 函数中的工作流程很简单,但是当进行单元测试时,我卡在了将参数传递给内部函数,或者模拟内部函数返回结果。
代码:
package myFunc
import (
myPackage
bookPackage
)
func Init() (err error) {
err = getResource(myPackage.GetPath())
...
}
func getResource(path string) (err error) {
// get resource from path ...
err := bookPackage.GetBook(path)
}
测试:
package myFunc
import "testing"
func TestInit(t *testing.T) {
if err := Init(); err != nil {
t.Fatal("test failed")
}
}
结果:
--- FAIL: TestInit (0.00s)
Failed to read path ...
这种情况的一般解决方案是什么?例如,如果 getResource() 调用 getBooks() 并且它的参数来自另一个来源?
如何在不实际运行的情况下模拟 getBooks() 返回结果?
谢谢,
最佳答案
我假设这不是真正的代码,因为您正在调用未导出的函数? myPackage.getPath()
永远不会起作用。
无论如何,我倾向于这样做的方式是导出任何我需要更改以进行测试的内容:
package myPackage
var Path string
func init() {
Path = "/path/to/default/path"
}
func GetPath() {
return Path
}
然后当您测试时,您可以将该变量重写为您需要的任何值:
package myFunc
import (
"testing"
"myPackage"
)
func TestInit(t *testing.T) {
myPackage.Path = "/test/path"
if err := Init(); err != nil {
t.Fatal("test failed")
}
}
关于testing - golang 单元测试 : inner function parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545023/