在每个测试之后使用的Golang测试方法:undefined: testing.M

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月8日 19:07:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/28925688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定