gpt4 book ai didi

testing - 找到 TestMain 多个定义

转载 作者:IT王子 更新时间:2023-10-29 01:12:36 27 4
gpt4 key购买 nike

如果我定义两个测试,每个测试都有自己的 TestMain 方法,go test 错误:“找到多个 TestMain 定义”

我能理解并期待这种行为,因为在同一个包中不应该有多个 TestMain。但是,我不知道现在该怎么办。每个测试套件都有自己的需求。我需要创建不同的 TestMain 来设置测试,当然,无需重命名我的包

我可以在其他语言中使用 beforeafter 等设置方法轻松做到这一点,这是测试类所独有的

我可能会去使用 testify的套房。遗憾的是,stdlib 不支持这一点。

你有什么建议吗?

最佳答案

您可以使用 M.Run .

func TestMain(m *testing.M) {
setup()
code := m.Run()
close()
os.Exit(code)
}

参见 subtest了解更多信息。

更详细的例子:

package main

import (
"testing"
)

func setup() {}
func teardown() {}

func setup2() {}
func teardown2() {}

func TestMain(m *testing.M) {
var wrappers = []struct {
Setup func()
Teardown func()
}{
{
Setup: setup,
Teardown: teardown,
},
{
Setup: setup2,
Teardown: teardown2,
},
}

for _, w := range wrappers {
w.Setup()
code := m.Run()
w.Teardown()

if code != 0 {
panic("code insn't null")
}
}
}

关于testing - 找到 TestMain 多个定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44552393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com