测试主函数存在多个定义

huangapple go评论71阅读模式
英文:

TestMain multiple definitions found

问题

如果我定义了两个测试,每个测试都有自己的TestMain方法,go test会报错:"multiple definitions found of TestMain"

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

在其他语言中,我可以很容易地使用像beforeafter这样的设置方法,这些方法是特定于测试类的。

我可能会去使用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 TestMains 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")
		}
	}
}

huangapple
  • 本文由 发表于 2017年6月15日 02:44:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/44552393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定