go / intermediate
Snippet
Defining Table-Driven Unit Tests
Table-driven testing is a clean pattern in Go that uses slice literals of anonymous structs to run multiple test cases. Using t.Run allows each case to run as a subtest, which provides clean reporting and selective execution.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package mainimport "testing"func Add(a, b int) int {return a + b}func TestAdd(t *testing.T) {tests := []struct {name stringa, b intexpected int}{{"positive numbers", 2, 3, 5},{"negative numbers", -1, -1, -2},{"mixed numbers", -5, 10, 5},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {result := Add(tt.a, tt.b)if result != tt.expected {t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)}})}}
Breakdown
1
tests := []struct {
Declares a slice of anonymous structs to hold input arguments and expected output.
2
for _, tt := range tests {
Iterates over each test case in the slice.
3
t.Run(tt.name, func(t *testing.T) {
Spawns a subtest named after the current test case.
4
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
Reports a failure with detailed context without stopping other test cases.