Subtests
Use subtests to structure related cases clearly and to isolate failures without duplicating test harness code.
Canonical guidance
- use
t.Runto name and isolate related cases - combine subtests with table-driven structure when it improves clarity
- keep subtest names meaningful for failure output
Use when
- grouped scenarios
- shared test harness with many variants
- selective test execution
Avoid
- deeply nested subtests that obscure control flow
- using subtests when a simple loop or a separate test would be clearer
Preferred pattern
t.Run("invalid input", func(t *testing.T) {
// ...
})
Anti-pattern
- anonymous or content-free subtest names that make failure output useless
Explanation: This anti-pattern is common because subtests are easy to nest, but excessive nesting obscures which behavior actually failed.
Why
- subtests improve diagnostics and organization when used sparingly and clearly
Related pages
Sources
- testing package - Go Team