2015-03-08 11:07
浏览 195


I am trying to repeat example from golang testing

package main

import (

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从 golang测试

func  TestSomeTest(t * testing.T){} 
func TestMain(m * testing.M){//每次测试后清洁} 

我要< code> TestMain 函数在每次测试后运行。

运行命令 go test

以及编译器 说

  ./ testingM_test.go:9:未定义:testing.M 

那么如何清洁后 执行每个测试?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyudun6465 2015-03-08 11:11

    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) {
        // os.Exit() does not respect defer statements
        ret := m.Run()

    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.

    点赞 评论

相关推荐 更多相似问题