Table-driven tests
Use table-driven tests when many cases share the same structure and assertions.
Canonical guidance
- use a table when cases differ mainly by input and expected output
- name cases when failure diagnosis matters
- combine with subtests when case isolation improves output
Use when
- parser tests
- validation matrices
- boundary and edge-case suites
Avoid
- forcing table-driven style onto tests with very different setup or behavior
- giant anonymous case tables with unclear intent
Preferred pattern
tests := []struct {
name string
in string
want int
}{
{name: "empty", in: "", want: 0},
}
Anti-pattern
- one enormous table spanning unrelated behavior domains
Explanation: This anti-pattern is common because the pattern is popular, but forcing unrelated scenarios into one table hides intent and makes cases harder to maintain.
Why
- table-driven tests reduce duplication while keeping case coverage explicit
Related pages
Sources
- TableDrivenTests - Go Team
- testing package - Go Team