我有一些我想在 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}},
)
}
游乐场链接: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]
最佳答案
首先,运行测试应该通过 go test
来完成。命令。
testing
中导出的某些类型和函数包是针对测试框架的,而不是给你的。引自 testing.RunTests()
:
RunTests is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.
它“必须”被导出,因为它早于“内部”包。
那里。你已经被警告过了。
如果您还想这样做,请调用
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()
功能。首先我们需要一个辅助类型(它实现了一个未导出的接口(interface)):
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
.
关于go - 在 Go 中以编程方式运行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67601236/