如何将TestMain(m *testing.M)限制在当前测试文件中?

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

How to restrict TestMain(m *testing.M) to the current test file

问题

是否可以将func TestMain(m *testing.M) {}限制在当前测试文件中,而不是同一包中的所有测试文件中?

假设在package blah中有两个测试文件:

blah_test.go

package blah

import "testing"

func TestMain(m *testing.M) {
	// 做一些花哨的事情
}

// 所有依赖于TestMain()的blah测试...

arg_test.go

package blah

import "testing"

// 所有不依赖于TestMain()的arg测试...

由于这两个测试文件都在同一个包中,TestMain()会在所有blah_test.go测试之前被调用(这是预期的),并且在所有arg_test.go测试之前被调用(这是意外的)。我希望TestMain()只在当前测试文件中触发,而不是整个包中的所有文件,但我没有找到任何提示表明这是可能的。

我尝试用init()替换TestMain(),但结果是一样的(这也是意外的)。除了在blah_test.go中创建自己的函数并更新所有blah_test.go测试以调用该函数之外,我还能做些什么呢?

英文:

Is it possible to restrict a func TestMain(m *testing.M) {} to the current test file, instead of to all test files in the same package?

Suppose in package blah I have the two test files:

blah_test.go:

package blah

import "testing"

func TestMain(m *testing.M) {
	// do something fancy
}

// all my blah tests that depend on TestMain()...

arg_test.go:

package blah

import "testing"

// all my arg tests that don't depend on TestMain()...

Since both of these test files are in the same package, TestMain() gets called before all blah_test.go tests (which is expected), and before all of my arg_test.go tests (this was unexpected). I'd love to have TestMain() only trigger for the current test file it's in, instead of to the entire package but can't see anything that suggests this is possible.

I attempted replacing TestMain() with an init(), but that does the same thing (which was also unexpected). Anything I can do here besides creating my own function in blah_test.go and updating all blah_test.go tests to hit that func?

答案1

得分: 4

go test在包上工作,而不是文件。你不能做你想做的事情。

英文:

go test works on packages not files. You cannot do what you want.

huangapple
  • 本文由 发表于 2021年7月16日 02:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/68399440.html
匿名

发表评论

匿名网友

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

确定