Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang testing method after each test: undefined: testing.M

Tags:

go

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?

like image 478
Maxim Yefremov Avatar asked May 02 '26 03:05

Maxim Yefremov


1 Answers

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.

like image 110
VonC Avatar answered May 05 '26 11:05

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!