如何使用Go中的测试包进行测试设置 [英] How can I do test setup using the testing package in Go

查看:73
本文介绍了如何使用Go中的测试包进行测试设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用测试包时,如何进行整体测试设置处理,为所有测试奠定基础 a>?

How can I do overall test setup processing which sets the stage for all the tests when using the testing package?

例如,在Nunit中有一个[SetUp]属性.

As an example in Nunit there is a [SetUp] attribute.

[TestFixture]
public class SuccessTests
{
  [SetUp] public void Init()
  { /* Load test data */ }
}

推荐答案

从Go 1.4开始,您可以执行设置/拆卸(无需在每次测试之前/之后复制功能).在主要部分此处中概述了该文档:

Starting with Go 1.4 you can implement setup/teardown (no need to copy your functions before/after each test). The documentation is outlined here in the Main section:

TestMain在主goroutine中运行,并且可以进行任何设置和 在致电m.Run之前,必须拆解.然后它应该调用 os.Exit,结果为m.Run

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),则将调用此功能而不是运行测试.在此函数中,我可以定义测试的运行方式.例如,我可以实现全局设置和拆卸:

It took me some time to figure out that this means that if a test contains a function func TestMain(m *testing.M) then this function will be called instead of running the test. And in this function I can define how the tests will run. For example I can implement global setup and teardown:

func TestMain(m *testing.M) {
    setup()
    code := m.Run() 
    shutdown()
    os.Exit(code)
}

在此处找到其他示例.

最新的TestMain功能已添加到Go的测试框架中 发布是针对多个测试用例的简单解决方案. TestMain 提供全局钩子以执行设置和关闭,控制 测试环境,在子进程中运行不同的代码或检查 测试代码泄漏的资源.大多数软件包都不需要 TestMain,但是对于那些时候它是一个受欢迎的补充 需要.

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.

这篇关于如何使用Go中的测试包进行测试设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆