算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
go-test-table-driven【设计与创意】Deep dive on table-driven tests in Go: when to use them, when to avoid them, struct design, subtest naming, advanced patterns like test matrices and shared setup, and refactoring bloated tables into clean ones. Use when writing table-driven tests, refactoring test tables, reviewing table test structure, or deciding whether table-driven is the right a…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
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.
Use a table only when ALL of these are true:
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.
setupMock/setupFunc function fields in
the struct mean the table is hiding complexity. Write explicit subtests.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.
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.Full field-pattern examples are in references/patterns.md.
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.
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := Transform(tt.input)
assert.Equal(t, tt.want, got)
})
}
tt := tt capture is
unnecessary. For Go <1.22 the capture is still required.t.Parallel() when the function under test has no side
effects and no shared mutable state.| 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 |
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.
name fieldsetupFunc or mockFunc fields in the structwantErr is a simple bool or sentinel, not a string matcht.Run wraps each case for named subtestst.Parallel() used only when function is side-effect-free