How can I do test setup using the testing package in Go

Issue

How can I do overall test setup processing which sets the stage for all the tests when using the testing package?

As an example in Nunit there is a [SetUp] attribute.

[TestFixture]
public class SuccessTests
{
  [SetUp] public void Init()
  { /* Load test data */ }
}

Solution

Starting with Go 1.4 you can implement setup/teardown (no need to copy your functions before/after each test). The documentation is outlined here in the Main section:

TestMain runs in the main goroutine and can do whatever setup and
teardown is necessary around a call to m.Run. It should then call
os.Exit with the result of m.Run

It took me some time to figure out that this means that if a test contains a function func TestMain(m *testing.M) then this function will be called instead of running the test. And in this function I can define how the tests will run. For example I can implement global setup and teardown:

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

A couple of other examples can be found here.

The TestMain feature added to Go’s testing framework in the latest
release is a simple solution for several testing use cases. TestMain
provides a global hook to perform setup and shutdown, control the
testing environment, run different code in a child process, or check
for resources leaked by test code. Most packages will not need a
TestMain, but it is a welcome addition for those times when it is
needed.

Answered By – Salvador Dali

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.