首先,运行测试应该通过go test 命令来完成。
testing 包中导出的某些类型和函数用于测试框架,而不适合您。引用testing.RunTests():
RunTests 是一个内部函数,但因为是跨包而被导出;它是“go test”命令实现的一部分。
它“必须”被导出,因为它早于“内部”包。
那里。您已收到警告。
如果您仍想这样做,请致电 testing.Main() 而不是 testing.RunTests()。
例如:
func TestGood(t *testing.T) {
}
func TestBad(t *testing.T) {
t.Error("This is a mocked failed test")
}
func main() {
testing.Main(
nil,
[]testing.InternalTest{
{"Good", TestGood},
{"Bad", TestBad},
},
nil, nil,
)
}
哪个会输出(在Go Playground上试试):
--- FAIL: Bad (0.00s)
prog.go:11: This is a mocked failed test
FAIL
如果您想捕捉测试的成功,请使用“较新的”testing.MainStart() 函数。
首先我们需要一个辅助类型(它实现了一个未导出的接口):
type testDeps struct{}
func (td testDeps) MatchString(pat, str string) (bool, error) { return true, nil }
func (td testDeps) StartCPUProfile(w io.Writer) error { return nil }
func (td testDeps) StopCPUProfile() {}
func (td testDeps) WriteProfileTo(string, io.Writer, int) error { return nil }
func (td testDeps) ImportPath() string { return "" }
func (td testDeps) StartTestLog(io.Writer) {}
func (td testDeps) StopTestLog() error { return nil }
func (td testDeps) SetPanicOnExit0(bool) {}
现在使用它:
m := testing.MainStart(testDeps{},
[]testing.InternalTest{
{"Good", TestGood},
{"Bad", TestBad},
},
nil, nil,
)
result := m.Run()
fmt.Println(result)
哪些输出(在Go Playground 上试试):
--- FAIL: Bad (0.00s)
prog.go:13: This is a mocked failed test
FAIL
1
如果所有测试都通过,result 将是0。