测试主函数存在多个定义

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

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

  1. func TestMain(m *testing.M) {
  2. setup()
  3. code := m.Run()
  4. close()
  5. os.Exit(code)
  6. }

有关更多信息,请参阅subtest

更详细的示例:

  1. package main
  2. import (
  3. "testing"
  4. )
  5. func setup() {}
  6. func teardown() {}
  7. func setup2() {}
  8. func teardown2() {}
  9. func TestMain(m *testing.M) {
  10. var wrappers = []struct {
  11. Setup func()
  12. Teardown func()
  13. }{
  14. {
  15. Setup: setup,
  16. Teardown: teardown,
  17. },
  18. {
  19. Setup: setup2,
  20. Teardown: teardown2,
  21. },
  22. }
  23. for _, w := range wrappers {
  24. w.Setup()
  25. code := m.Run()
  26. w.Teardown()
  27. if code != 0 {
  28. panic("code isn't null")
  29. }
  30. }
  31. }
英文:

You can use M.Run.

  1. func TestMain(m *testing.M) {
  2. setup()
  3. code := m.Run()
  4. close()
  5. os.Exit(code)
  6. }

See subtest for additional info.

More detailed example:

  1. package main
  2. import (
  3. "testing"
  4. )
  5. func setup() {}
  6. func teardown() {}
  7. func setup2() {}
  8. func teardown2() {}
  9. func TestMain(m *testing.M) {
  10. var wrappers = []struct {
  11. Setup func()
  12. Teardown func()
  13. }{
  14. {
  15. Setup: setup,
  16. Teardown: teardown,
  17. },
  18. {
  19. Setup: setup2,
  20. Teardown: teardown2,
  21. },
  22. }
  23. for _, w := range wrappers {
  24. w.Setup()
  25. code := m.Run()
  26. w.Teardown()
  27. if code != 0 {
  28. panic("code insn't null")
  29. }
  30. }
  31. }

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:

确定