unit-testing - 如何使用 Go 中的测试包进行测试设置

标签 unit-testing go

当使用 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/

相关文章:

java - 即使通过java中的测试传递值,属性也为空?

c# - Moq:Lambda 表达式作为参数并在返回中评估它们

c++ - 单元测试对实例变量函数的调用

python - 模糊逻辑: How to detect when a 404 is not actually an error page?

python - 如何对 python 版本开关进行单元测试

go - 为什么我的程序在添加 time.sleep 时挂起?

go - 你如何在golang中返回一个非原始类型的变量

go - 如何在返回时使用路由名称作为全局变量

go - 在端点 REST API 的 GoConvey 测试期间跳过某些包含静态内容的文件夹

go - 绑定(bind): The requested address is not valid in its context