gpt4 book ai didi

python - Golang 测试中的 fixture

转载 作者:IT王子 更新时间:2023-10-29 01:18:28 24 4
gpt4 key购买 nike

来自 python 世界,fixtures 非常有用(Fixtures 为可重用状态/支持逻辑定义了 Python 契约,主要用于单元测试)。我想知道 Golang 中是否有类似的支持,它可以让我使用一些预定义的装置运行我的测试,比如设置服务器、拆除它、在每次运行测试时做一些重复的任务?有人能给我指出一些在 Golang 中做同样事情的例子吗?

最佳答案

如果你想使用标准的 Go 测试工具,你可以定义一个带有签名的函数 TestMain(m *testing.M) 并将你的 fixture 代码放在那里。

来自testing package wiki :

It is sometimes necessary for a test program to do extra setup or teardown before or after testing. It is also sometimes necessary for a test to control which code runs on the main thread. To support these and other cases, if a test file contains a function:

func TestMain(m *testing.M)

then the generated test will call TestMain(m) instead of running the tests directly. 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. When TestMain is called, flag.Parse has not been run. If TestMain depends on command-line flags, including those of the testing package, it should call flag.Parse explicitly.

A simple implementation of TestMain is:

func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}

关于python - Golang 测试中的 fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com