英文:
golang testing method after each test: undefined: testing.M
问题
我正在尝试重复golang testing中的示例。
package main
import (
"testing"
)
func TestSomeTest(t *testing.T) {}
func TestMain(m *testing.M) { // 在每个测试之后进行清理 }
我希望TestMain
函数在每个测试之后运行。
运行命令go test
时,编译器报错:
./testingM_test.go:9: undefined: testing.M
那么如何在执行每个测试后进行清理呢?
英文:
I am trying to repeat example from golang testing
package main
import (
"testing"
)
func TestSomeTest(t *testing.T) {}
func TestMain(m *testing.M) { // cleaning after each test}
I want TestMain
function to run after every test.
Running command go test
And the compiler says
./testingM_test.go:9: undefined: testing.M
So how to clean after executing every test?
答案1
得分: 8
检查你的go version
输出:这是针对仅适用于go 1.4+的。
测试包有一个新的功能,可以更好地控制运行一组测试。如果测试代码包含一个函数
func TestMain(m *testing.M)
那个函数将被调用,而不是直接运行测试。
M
结构体包含了访问和运行测试的方法。
你可以在这里看到使用了这个特性:
TestMain()
的引入使得只运行这些迁移一次成为可能。现在的代码看起来像这样:
func TestSomeFeature(t *testing.T) {
defer models.TestDBManager.Reset()
// 进行测试
}
func TestMain(m *testing.M) {
models.TestDBManager.Enter()
// os.Exit()不会遵守defer语句
ret := m.Run()
models.TestDBManager.Exit()
os.Exit(ret)
}
虽然每个测试仍然必须自己清理,但这只涉及恢复初始数据,比执行模式迁移要快得多。
英文:
Check you go version
output: this is for go 1.4+ only.
> The testing package has a new facility to provide more control over running a set of tests. If the test code contains a function
func TestMain(m *testing.M)
> that function will be called instead of running the tests directly.
The M
struct contains methods to access and run the tests.
You can see that feature used here:
> The introduction of TestMain()
made it possible to run these migrations only once. The code now looks like this:
func TestSomeFeature(t *testing.T) {
defer models.TestDBManager.Reset()
// Do the tests
}
func TestMain(m *testing.M) {
models.TestDBManager.Enter()
// os.Exit() does not respect defer statements
ret := m.Run()
models.TestDBManager.Exit()
os.Exit(ret)
}
> While each test must still clean up after itself, that only involves restoring the initial data, which is way faster than doing the schema migrations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论