capypad
0 day streak
go / intermediate
Snippet

Implementing Table-Driven Tests

Table-driven testing is a Go idiom where test cases are defined as a slice of anonymous structs. This makes it easy to add new scenarios and ensures consistent testing logic across multiple inputs.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func TestAdd(t *testing.T) {
tests := []struct {
a, b, want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
 
for _, tt := range tests {
got := Add(tt.a, tt.b)
if got != tt.want {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
}
}
Breakdown
1
struct { a, b, want int }
Defines the structure for input parameters and expected output.
2
range tests
Iterates through each defined test case in the table.
3
t.Errorf(...)
Reports a failure but allows the loop to continue with other test cases.