duanji9264 2015-03-08 11:07
浏览 314
已采纳

每次测试后的golang测试方法:未定义: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条回答 默认 最新

  • 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) {
        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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失