Table-driven tests
A table-driven test is a slice of cases — input, want, name — and a loop that runs the same assertions on each. One test function covers many examples without copy-paste.
Detailed Explanation
You are testing a parser. Five inputs belong in a slice of structs, not five TestParseX functions that differ by one string. The struct holds name, in, want, and maybe wantErr. The loop calls t.Run(tc.name, ...) so -run can pick a case and failures name the row.
The case struct is the documentation. Field names tell the next reader what varies. Anonymous structs in the composite literal are the usual style. Keep cases in a []struct{...}{ {...}, ... } next to the loop, or in a var cases = ... if they are reused.
Compare with == or reflect.DeepEqual or go-cmp. For structs without slices, == is enough. For slices and maps, reflect.DeepEqual or cmp.Diff is clearer. Do not invent a one-off pretty printer per test file unless the diff is huge.
Errors in the table. A wantErr bool or a wantErr error with errors.Is is better than a string match on err.Error().
What it costs. A little more setup than one assertion. The payoff is adding a row instead of a function. Shared setup that is expensive belongs in the outer test, not copied per case; per-case setup belongs inside t.Run.
Code Examples
package parse
import "testing"
func TestParsePort(t *testing.T) {
tests := []struct {
name string
in string
want int
wantErr bool
}{
{name: "ok", in: "8080", want: 8080},
{name: "empty", in: "", wantErr: true},
{name: "neg", in: "-1", wantErr: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := parsePort(tc.in)
if tc.wantErr {
if err == nil {
t.Fatal("expected error")
}
return
}
if err != nil {
t.Fatal(err)
}
if got != tc.want {
t.Fatalf("got %d want %d", got, tc.want)
}
})
}
}
func parsePort(s string) (int, error) {
if s == "8080" {
return 8080, nil
}
return 0, errBad
}
var errBad = errString("bad")
type errString string
func (e errString) Error() string { return string(e) }Common Gotchas
Loop variable capture in `t.Parallel()`
pass `tc := tc` (or rely on Go 1.22 per-iteration) before `t.Parallel()`.
A missing `t.Run` name makes `-run` and logs harder
name every row.
Shared mutable `tc` in parallel subtests races
copy the case.