go - 在 Go 中以编程方式运行测试

标签 go testing

我有一些我想在 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/

相关文章:

python - 使用 Django/Python 获得最大测试覆盖率的最佳实践?

testing - 无需安装 Visual Studio 的编码 UI 测试

go - 在golang中创建二维字符串数组

go - 使用 sarama 编写 Kafka 制作人时无效的时间戳

go - 在 switch 中使用关键字 type 是什么意思?

go - 如果调用的函数来自不同的包,如何同步 goroutine?

java - 在测试环境中实例化 context.xml 的位置

c# - 如何测试返回 IEnumerable<int> 的方法?

linux - 无限循环与Cron工作

javascript - 如何衡量 React App 随时间推移的首次渲染性能?