Go Table-Driven Tests
Table-driven tests are a powerful Go idiom — when used correctly. Most
codebases either underuse them (10 copy-paste tests) or overuse them
(complex branching logic in a 200-line struct). This skill covers the
sweet spot.
Detailed reference material, loaded on demand:
references/patterns.md — full worked examples: canonical tables,
wantErr/wantErrIs, parallel tables, map-based tables, error-only
tables, struct alignment for readability.
references/refactoring.md — recognizing bloated tables and rewriting
them as explicit subtests, with before/after examples.
Read a reference file only when the summary below is not enough for the
task at hand.
1. When Table-Driven Tests Shine
Use a table only when ALL of these are true:
- Same function under test across all cases
- Same assertion pattern — input in, output out, compare
- Cases differ only in data, not in setup or verification logic
- 3+ cases — fewer than 3, explicit tests are clearer
Canonical use case: pure functions, parsers, validators, formatters.
func TestParseSize(t *testing.T) {
tests := []struct {
name string
input string
want int64
wantErr bool
}{
{name: "plain bytes", input: "1024", want: 1024},
{name: "kilobytes suffix", input: "4KB", want: 4096},
{name: "empty string", input: "", wantErr: true},
{name: "negative size", input: "-1", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseSize(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
Every case has the same shape, the loop body is a few lines, and adding
a case is one struct literal. No branching, no conditionals.
2. When NOT to Use Table-Driven Tests
- Complex per-case setup —
setupMock/setupFunc function fields in
the struct mean the table is hiding complexity. Write explicit subtests.
- Fewer than 3 cases — the struct definition is more code than two
plain test functions.
- Multiple branching paths —
if tt.shouldError / if tt.wantRedirect
in the loop body means each branch is a different test pretending to
share a structure. Split it.
See references/refactoring.md for before/after rewrites of each smell.
3. Struct Design Rules
- Every field must vary between at least 2 cases. A field with the
same value everywhere is setup — move it outside the table.
- Name the
name field as a short sentence describing the scenario:
"returns error for negative amount", not "case1" or "success".
wantErr bool for "should it error?" — check it first and return
early in the loop body.
wantErrIs error with a sentinel when the caller must detect a
specific error; assert with require.ErrorIs.
- ≤5 fields. More means the scenario is too complex for a table —
split into separate test functions.
Full field-pattern examples are in references/patterns.md.
4. The Loop Body Must Be Trivial
The point of a table test is identical execution logic for every case.
Keep the loop body under ~10 lines: call, error check, comparison.
If it accumulates conditionals or per-case setup, the table has outgrown
its usefulness — refactor into explicit subtests.
5. Parallel Table Tests
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := Transform(tt.input)
assert.Equal(t, tt.want, got)
})
}
- Go 1.22+ scopes the loop variable per iteration —
tt := tt capture is
unnecessary. For Go <1.22 the capture is still required.
- Only use
t.Parallel() when the function under test has no side
effects and no shared mutable state.
6. Refactoring Bloated Tables
| Symptom |
Fix |
| Struct has 8+ fields |
Split into multiple test functions by scenario |
setupFunc field in struct |
Extract to separate subtests with explicit setup |
if tt.shouldX in loop body |
Each branch is a different test — split it |
| Same 3 fields identical in every case |
Move to shared setup outside the table |
| Adding a case requires understanding all others |
Table has grown beyond its useful life |
Decision Flowchart
Is the function pure (input → output, no side effects)?
Yes → table test is probably ideal. Go to 2.
No → consider explicit subtests first.
Do all cases share the exact same assertion pattern?
Yes → table test. Go to 3.
No → explicit subtests.
Can each case be expressed in ≤5 struct fields?
Yes → table test.
No → split by scenario into separate test functions.
Is the loop body ≤10 lines?
Yes → you're golden.
No → the table is hiding complexity. Refactor.
Verification Checklist
- Table struct has only fields that vary between cases
- Every case has a descriptive
name field
- Loop body is ≤10 lines with no branching
- No
setupFunc or mockFunc fields in the struct
wantErr is a simple bool or sentinel, not a string match
- Cases cover: happy path, error path, edge cases (empty, nil, zero, max)
t.Run wraps each case for named subtests
t.Parallel() used only when function is side-effect-free
1---
2name: go-test-table-driven
3description: >
4 Deep dive on table-driven tests in Go: when to use them, when to avoid
5 them, struct design, subtest naming, advanced patterns like test matrices
6 and shared setup, and refactoring bloated tables into clean ones. Use when
7 writing table-driven tests, refactoring test tables, reviewing table test
8 structure, or deciding whether table-driven is the right approach. Trigger
9 examples: "table-driven test", "table test", "test cases struct", "test
10 matrix", "parametrize tests", "data-driven test", "refactor test table".
11 Not for: general test strategy, mocks, golden files, fuzzing
12 (go-test-quality), benchmarks (go-performance-review).
13user-invocable: true
14license: MIT
15compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
16allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
17metadata:
18 source: https://skillmd.com/skills/gabrielmoreira/go-test-table-driven
19 author: eduardo-sl
20 version: "1.2.1"
21---
22
23# Go Table-Driven Tests
24
25Table-driven tests are a powerful Go idiom — when used correctly. Most
26codebases either underuse them (10 copy-paste tests) or overuse them
27(complex branching logic in a 200-line struct). This skill covers the
28sweet spot.
29
30Detailed reference material, loaded on demand:
31
32- `references/patterns.md` — full worked examples: canonical tables,
33 `wantErr`/`wantErrIs`, parallel tables, map-based tables, error-only
34 tables, struct alignment for readability.
35- `references/refactoring.md` — recognizing bloated tables and rewriting
36 them as explicit subtests, with before/after examples.
37
38Read a reference file only when the summary below is not enough for the
39task at hand.
40
41## 1. When Table-Driven Tests Shine
42
43Use a table only when ALL of these are true:
44
45- **Same function** under test across all cases
46- **Same assertion pattern** — input in, output out, compare
47- **Cases differ only in data**, not in setup or verification logic
48- **3+ cases** — fewer than 3, explicit tests are clearer
49
50Canonical use case: pure functions, parsers, validators, formatters.
51
52```go
53func TestParseSize(t *testing.T) {
54 tests := []struct {
55 name string
56 input string
57 want int64
58 wantErr bool
59 }{
60 {name: "plain bytes", input: "1024", want: 1024},
61 {name: "kilobytes suffix", input: "4KB", want: 4096},
62 {name: "empty string", input: "", wantErr: true},
63 {name: "negative size", input: "-1", wantErr: true},
64 }
65
66 for _, tt := range tests {
67 t.Run(tt.name, func(t *testing.T) {
68 got, err := ParseSize(tt.input)
69 if tt.wantErr {
70 require.Error(t, err)
71 return
72 }
73 require.NoError(t, err)
74 assert.Equal(t, tt.want, got)
75 })
76 }
77}
78```
79
80Every case has the same shape, the loop body is a few lines, and adding
81a case is one struct literal. No branching, no conditionals.
82
83## 2. When NOT to Use Table-Driven Tests
84
85- **Complex per-case setup** — `setupMock`/`setupFunc` function fields in
86 the struct mean the table is hiding complexity. Write explicit subtests.
87- **Fewer than 3 cases** — the struct definition is more code than two
88 plain test functions.
89- **Multiple branching paths** — `if tt.shouldError` / `if tt.wantRedirect`
90 in the loop body means each branch is a different test pretending to
91 share a structure. Split it.
92
93See `references/refactoring.md` for before/after rewrites of each smell.
94
95## 3. Struct Design Rules
96
971. **Every field must vary between at least 2 cases.** A field with the
98 same value everywhere is setup — move it outside the table.
992. **Name the `name` field as a short sentence** describing the scenario:
100 `"returns error for negative amount"`, not `"case1"` or `"success"`.
1013. **`wantErr bool` for "should it error?"** — check it first and `return`
102 early in the loop body.
1034. **`wantErrIs error` with a sentinel** when the caller must detect a
104 specific error; assert with `require.ErrorIs`.
1055. **≤5 fields.** More means the scenario is too complex for a table —
106 split into separate test functions.
107
108Full field-pattern examples are in `references/patterns.md`.
109
110## 4. The Loop Body Must Be Trivial
111
112The point of a table test is identical execution logic for every case.
113Keep the loop body under ~10 lines: call, error check, comparison.
114If it accumulates conditionals or per-case setup, the table has outgrown
115its usefulness — refactor into explicit subtests.
116
117## 5. Parallel Table Tests
118
119```go
120for _, tt := range tests {
121 t.Run(tt.name, func(t *testing.T) {
122 t.Parallel()
123 got := Transform(tt.input)
124 assert.Equal(t, tt.want, got)
125 })
126}
127```
128
129- Go 1.22+ scopes the loop variable per iteration — `tt := tt` capture is
130 unnecessary. For Go <1.22 the capture is still required.
131- Only use `t.Parallel()` when the function under test has no side
132 effects and no shared mutable state.
133
134## 6. Refactoring Bloated Tables
135
136| Symptom | Fix |
137|---|---|
138| Struct has 8+ fields | Split into multiple test functions by scenario |
139| `setupFunc` field in struct | Extract to separate subtests with explicit setup |
140| `if tt.shouldX` in loop body | Each branch is a different test — split it |
141| Same 3 fields identical in every case | Move to shared setup outside the table |
142| Adding a case requires understanding all others | Table has grown beyond its useful life |
143
144## Decision Flowchart
145
1461. **Is the function pure (input → output, no side effects)?**
147 Yes → table test is probably ideal. Go to 2.
148 No → consider explicit subtests first.
149
1502. **Do all cases share the exact same assertion pattern?**
151 Yes → table test. Go to 3.
152 No → explicit subtests.
153
1543. **Can each case be expressed in ≤5 struct fields?**
155 Yes → table test.
156 No → split by scenario into separate test functions.
157
1584. **Is the loop body ≤10 lines?**
159 Yes → you're golden.
160 No → the table is hiding complexity. Refactor.
161
162## Verification Checklist
163
1641. Table struct has only fields that vary between cases
1652. Every case has a descriptive `name` field
1663. Loop body is ≤10 lines with no branching
1674. No `setupFunc` or `mockFunc` fields in the struct
1685. `wantErr` is a simple bool or sentinel, not a string match
1696. Cases cover: happy path, error path, edge cases (empty, nil, zero, max)
1707. `t.Run` wraps each case for named subtests
1718. `t.Parallel()` used only when function is side-effect-free