gpt4 book ai didi

每次测试后的golang测试方法 : undefined: testing. M

转载 作者:IT王子 更新时间:2023-10-29 00:54:14 34 4
gpt4 key购买 nike

我正在尝试重复 golang testing 中的示例

package main

import (
"testing"
)

func TestSomeTest(t *testing.T) {}

func TestMain(m *testing.M) { // cleaning after each test}

我希望 TestMain 函数在每次测试后运行。

运行命令go test

编译器说

./testingM_test.go:9: undefined: testing.M

那么每次执行完测试后如何清理呢?

最佳答案

检查你的 go version 输出:这是 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.


可以看到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.

关于每次测试后的golang测试方法 : undefined: testing. M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925688/

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