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

标签 go

我正在尝试重复 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/

相关文章:

string - 如何检查附加 slice 是否等于字符串?

google-app-engine - 在 appspot.com 上解析 64 位 int 与在本地主机上不同?

sql - 并发安全访问golang中的数据库

for-loop - 我如何通过 Go 中的 for 循环将数字加倍?

amazon-web-services - 如何在golang中模拟request.Request

image - 去图像处理

go - Go构造函数中的返回值与指针

json - golang 解析一个复杂的字符串为json

go - golang环境变量存放在哪里?

当找不到值时,Gorm 返回空对象而不是默认对象