我有一些测试想要在 Go 中以编程方式运行。我正在尝试使用testing.RunTests,但它引发了运行时错误。我也无法弄清楚代码有什么问题。
它看起来是这样的:
package main
import (
"testing"
)
func TestSomething(t *testing.T) {
if false {
t.Error("This is a mocked failed test")
}
}
func main() {
testing.RunTests(func(pat, str string) (bool, error) { return true, nil },
[]testing.InternalTest{
{"Something", TestSomething}},
)
}
Run Code Online (Sandbox Code Playgroud)
游乐场链接:https://play.golang.org/p/BC5MG8WXYGD
我收到的错误是:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4b5948]
Run Code Online (Sandbox Code Playgroud)
首先,运行测试应该通过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,
)
}
Run Code Online (Sandbox Code Playgroud)
它将输出(在Go Playground上尝试):
--- FAIL: Bad (0.00s)
prog.go:11: This is a mocked failed test
FAIL
Run Code Online (Sandbox Code Playgroud)
如果您想捕获测试的成功,请使用“更新”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) {}
Run Code Online (Sandbox Code Playgroud)
现在使用它:
m := testing.MainStart(testDeps{},
[]testing.InternalTest{
{"Good", TestGood},
{"Bad", TestBad},
},
nil, nil,
)
result := m.Run()
fmt.Println(result)
Run Code Online (Sandbox Code Playgroud)
哪个输出(在Go Playground上尝试):
--- FAIL: Bad (0.00s)
prog.go:13: This is a mocked failed test
FAIL
1
Run Code Online (Sandbox Code Playgroud)
如果所有测试都通过,result将会是0。