【问题标题】:How to restrict TestMain(m *testing.M) to the current test file如何将 TestMain(m *testing.M) 限制为当前测试文件
【发布时间】:2021-09-24 16:39:12
【问题描述】:

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

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

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()...

由于这两个测试文件都在同一个包中,TestMain() 在所有blah_test.go 测试之前被调用(这是预期的),在我所有的arg_test.go 测试之前 >(这是出乎意料的)。我希望TestMain() 仅触发它所在的当前测试文件,而不是整个包,但看不到任何表明这是可能的东西。

我尝试将TestMain() 替换为init(),但效果相同(这也是意料之外的)。除了在blah_test.go 中创建自己的函数并更新所有blah_test.go 测试以达到该函数之外,我还能在这里做什么?

【问题讨论】:

  • 为什么不能从TestMain 调用所有测试?它本质上是正常的操作模式,只是给你一个挂钩到测试包内部通常调用的内容。否则,通常的构建约束也适用于测试文件,这是区分包中文件的唯一方法。

标签: go testing


【解决方案1】:

go test 适用于包而不是文件。你不能为所欲为。

【讨论】:

  • 哈哈,有道理。我最近才发现/使用TestMain 并挂断了我没有考虑过的用途。谢谢!
猜你喜欢
  • 2011-02-04
  • 2020-01-16
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多