How to Use Table-Driven Tests in Go

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)
			}
		})
	}
}