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

每次测试后的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 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线