Table-Driven Tests
Parameterized tests with subtests
What are table-driven tests?
Table-driven tests define a slice of test cases (inputs and expected outputs) and loop over them with a single test body. They reduce duplication and make adding cases trivial.
Basic pattern
Define a struct for each case, loop with t.Run, and report failures with the case name:
tests := []struct {
name string
input int
want int
}{
{"zero", 0, 0},
{"positive", 3, 9},
{"negative", -2, 4},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Square(tt.input)
if got != tt.want {
t.Errorf("Square(%d) = %d; want %d", tt.input, got, tt.want)
}
})
}