go / expert
Snippet
Global Test Lifecycle Control via testing.M Setup and Teardown Hooks
In Go, custom package-level test suite setup and teardown is achieved by defining a TestMain function accepting a *testing.M argument. Calling m.Run() executes all package tests, returning an exit code that must be passed to os.Exit.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package mainimport ("fmt""os""testing")var globalResource stringfunc TestMain(m *testing.M) {globalResource = "initialized_db_connection"code := m.Run()globalResource = ""fmt.Println("Cleaned up global test resources")os.Exit(code)}func TestDatabaseOperation(t *testing.T) {if globalResource == "" {t.Fatal("Global resource was not initialized prior to test execution")}}
Breakdown
1
func TestMain(m *testing.M) {
Defines the custom entry point for the package's test binary.
2
code := m.Run()
Triggers the execution of all standard Test* functions within the current package.
3
os.Exit(code)
Explicitly exits the process returning the status code from m.Run().