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
TestMainruns instead of the tests;m.Runruns them.- Set up before, tear down after, then exit with the code.
testing.Shortlets a flag skip the slow ones.
Keywords and builtins used here
funcifstringvar
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.
Step 2 of 2 in Running them, step 12 of 13 in Testing.