Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestMain multiple definitions found

Tags:

If I define, two tests, each with its own TestMain method, go test errors: "multiple definitions found of TestMain".

I can understand and was expecting this behaviour actually, because, there should not be more than one TestMain in the same package. However, I don't know what to do now. Each test suite has its own needs. I need to create distinct TestMains to setup the tests, of course, without renaming my packages.

I could do that easily in other languages with setup methods like before, after, which is unique to a test class.

I'll probably go and use testify's suites. Sad that this is not supported in stdlib.

Do you have any suggestions?

like image 411
Inanc Gumus Avatar asked Jun 14 '17 18:06

Inanc Gumus


People also ask

What is TestMain?

Basically the TestMain function provides more control over running tests than was available in the prior releases of Go. So 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.

What does TestMain do golang?

TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m. Run. m. Run will return an exit code that may be passed to os.


1 Answers

You can use M.Run.

func TestMain(m *testing.M) {
    setup()
    code := m.Run() 
    close()
    os.Exit(code)
}

See subtest for additional info.

More detailed example:

package main

import (
    "testing"
)

func setup()    {}
func teardown() {}

func setup2()    {}
func teardown2() {}

func TestMain(m *testing.M) {
    var wrappers = []struct {
        Setup    func()
        Teardown func()
    }{
        {
            Setup:    setup,
            Teardown: teardown,
        },
        {
            Setup:    setup2,
            Teardown: teardown2,
        },
    }

    for _, w := range wrappers {
        w.Setup()
        code := m.Run()
        w.Teardown()

        if code != 0 {
            panic("code insn't null")
        }
    }
}
like image 117
Oleg Kovalov Avatar answered Oct 09 '22 04:10

Oleg Kovalov