Go Test Main
In this tutorial, you'll learn about Go Test: TestMain Setup. We cover key concepts, practical examples, and best practices.
TestMain -- Use TestMain to set up and tear down package-level test fixtures like databases and servers.
The Problem
TestMain runs once per package before and after all tests. Use it for expensive setup that should not be repeated per test.
Wrong
// Setup repeated across many tests:
func TestA(t *testing.T) {
db := setupDB() // Repeated
defer db.Close()
}
func TestB(t *testing.T) {
db := setupDB() // Repeated
defer db.Close()
}
Output:
// Setup runs for every test. Slow.
Right
func TestMain(m *testing.M) {
// Setup
db := setupDB()
code := m.Run() // Run all tests
// Teardown
db.Close()
os.Exit(code)
}
Output:
// One-time setup and teardown for all tests in package
Prevention
- Define TestMain(m *testing.M) in one file per package
- Call m.Run() to execute all tests
- os.Exit(m.Run()) for proper exit code
- One-time setup: DB connection, test server, test data
- Cleanup after m.Run() returns
Common Mistakes with test main
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro