typestar

TestMain in Go

One place for package-level setup, and the exit code is yours to return.

var fixtures string

func TestMain(m *testing.M) {
    fixtures = "loaded"          // setup
    code := m.Run()              // the tests
    fixtures = ""                // teardown
    os.Exit(code)
}

func TestUsesFixtures(t *testing.T) {
    if fixtures != "loaded" {
        t.Fatal("setup did not run")
    }
}

func TestSlow(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping in short mode")
    }
    time.Sleep(time.Millisecond)
}

How it works

  1. TestMain runs instead of the tests; m.Run runs them.
  2. Set up before, tear down after, then exit with the code.
  3. testing.Short lets a flag skip the slow ones.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
403
Tokens
92
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 2 of 2 in Running them, step 12 of 13 in Testing.

← Previous Next →