Define a slice of test cases and loop through them with t.Run to validate multiple inputs in a single Go test function.
Use table-driven tests by defining a slice of test cases, looping over them with t.Run, and asserting results inside the loop.
func TestAdd(t *testing.T) {
tests := []struct {
a, b, want int
}{
{1, 2, 3},
{0, 0, 0},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("%d+%d", tt.a, tt.b), func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
Table-driven tests let you run the same test logic against many different inputs by listing them in a table. You define a list of scenarios with inputs and expected results, then loop through them to check each one automatically. It is like checking a grocery list against your cart to ensure every item is correct without writing a separate check for each item.