Test helpers
Use `t.Helper` and small helper functions to remove repetition without hiding test intent.
Canonical guidance
- mark failing helpers with
t.Helper() - keep helpers narrow and behavior-focused
- let the test body still read like the scenario being validated
Use when
- fixture setup
- repeated assertions with good failure messages
- shared test server or temporary directory helpers
Avoid
- helpers that hide all the meaningful assertions
- custom assertion DSLs that are harder to debug than plain Go
- passing
testing.Teverywhere when plain values would suffice
Preferred pattern
func mustTempFile(t *testing.T, body string) string {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "*.txt")
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteString(body); err != nil {
t.Fatal(err)
}
return f.Name()
}
Anti-pattern
- building a huge custom helper layer that makes ordinary test failures impossible to trace
Explanation: This anti-pattern is tempting because reuse feels clean, but tests lose readability and local debugging signal.
Why
- small helpers reduce noise while preserving the directness of ordinary Go tests
Related pages
Sources
- testing package - Go Team