当使用 testing package 时,如何进行整体测试设置处理,为所有测试奠定基础?
例如,在 Nunit 中有一个 [SetUp]
属性。
[TestFixture]
public class SuccessTests
{
[SetUp] public void Init()
{ /* Load test data */ }
}
最佳答案
从 Go 1.4 开始,您可以实现 setup/teardown(无需在每次测试之前/之后复制您的函数)。文档概述 here在主要部分:
TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run. It should then call os.Exit with the result of m.Run
我花了一些时间才弄清楚这意味着如果一个测试包含一个函数 func TestMain(m *testing.M)
那么这个函数将被调用而不是运行测试。在这个函数中,我可以定义测试将如何运行。例如我可以实现全局设置和拆卸:
func TestMain(m *testing.M) { setup() code := m.Run() shutdown() os.Exit(code) }
其他几个例子can be found here .
The TestMain feature added to Go’s testing framework in the latest release is a simple solution for several testing use cases. TestMain provides a global hook to perform setup and shutdown, control the testing environment, run different code in a child process, or check for resources leaked by test code. Most packages will not need a TestMain, but it is a welcome addition for those times when it is needed.
关于unit-testing - 如何使用 Go 中的测试包进行测试设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729790/