英文:
TestMain multiple definitions found
问题
如果我定义了两个测试,每个测试都有自己的TestMain
方法,go test
会报错:"multiple definitions found of TestMain"
。
我可以理解并且预料到这种行为,因为在同一个包中不应该有多个TestMain。然而,我现在不知道该怎么办。每个测试套件都有自己的需求。我需要创建不同的TestMain
来设置测试,当然,不能重命名我的包。
在其他语言中,我可以很容易地使用像before
、after
这样的设置方法,这些方法是特定于测试类的。
我可能会去使用testify的测试套件。可惜标准库不支持这个功能。
你有什么建议吗?
英文:
If I define, two tests, each with its own TestMain
method, go test
errors: "multiple definitions found of TestMain"
.
I can understand and was expecting this behaviour actually, because, there should not be more than one TestMain in the same package. However, I don't know what to do now. Each test suite has its own needs. I need to create distinct TestMain
s to setup the tests, of course, without renaming my packages.
I could do that easily in other languages with setup methods like before
, after
, which is unique to a test class.
I'll probably go and use testify's suites. Sad that this is not supported in stdlib.
Do you have any suggestions?
答案1
得分: 4
你可以使用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 isn't null")
}
}
}
英文:
You can use M.Run.
func TestMain(m *testing.M) {
setup()
code := m.Run()
close()
os.Exit(code)
}
See subtest for additional info.
More detailed example:
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")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论