golang/go · error
multiple definitions of TestMain
Error message
multiple definitions of TestMain
What it means
A Go test binary may declare at most one func TestMain(m *testing.M). While scanning *_test.go functions, the loader appends a TestMain match only if none was recorded; encountering a second valid TestMain (correct name and signature M) returns this error and aborts test compilation.
Source
Thrown at src/cmd/go/internal/load/test.go:764
continue
}
if n.Recv != nil {
continue
}
name := n.Name.String()
switch {
case name == "TestMain":
if isTestFunc(n, "T") {
t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
*doImport, *seen = true, true
continue
}
err := checkTestFunc(n, "M")
if err != nil {
return err
}
if t.TestMain != nil {
return errors.New("multiple definitions of TestMain")
}
t.TestMain = &testFunc{pkg, name, "", false}
*doImport, *seen = true, true
case isTest(name, "Test"):
err := checkTestFunc(n, "T")
if err != nil {
return err
}
t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
*doImport, *seen = true, true
case isTest(name, "Benchmark"):
err := checkTestFunc(n, "B")
if err != nil {
return err
}
t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
*doImport, *seen = true, true
case isTest(name, "Fuzz"):View on GitHub (pinned to b6b368adc5)
Solutions
- Keep a single TestMain in one _test.go file and delete the duplicates.
- Consolidate setup from multiple TestMain functions into one, calling shared helper functions.
- Move per-file setup into TestMain-less helpers (e.g. t.Helper functions or sync.Once init).
Example fix
// before: a_test.go and b_test.go both define TestMain // after: keep TestMain only in main_test.go; // other files call shared setup() helpers from individual TestXxx
Defensive patterns
Strategy: validation
Validate before calling
// Fail fast in CI before `go test`: // if [ "$(grep -rn 'func TestMain' *_test.go | wc -l)" -gt 1 ]; then // echo "multiple TestMain"; exit 1; fi
Prevention
- Grep for `func TestMain` whenever you copy a test setup file into a package.
- Consolidate setup into a single main_test.go per package.
When it happens
Trigger: Two or more *_test.go files in the same Go package each define `func TestMain(m *testing.M)`.
Common situations: Copy-pasting a test setup file that already has TestMain; merging test helper modules each carrying their own TestMain; pulling in a testutil package whose example file defines TestMain.
Related errors
- import cycle not allowed in test
- multiple //go:build comments
- import cycle not allowed
- use of vendored package not allowed
- binary-only packages are no longer supported
AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12).
Data as JSON: /api/errors/3bcc32f59e33d97c.
Report an issue: GitHub.