go / intermediate
Snippet
Writing Maintainable Table-Driven Unit Tests
Table-driven testing is an idiomatic pattern in Go. By defining a list of test cases in a slice of structs, you can easily add new test inputs and expected outputs without duplicating assertion logic, leading to cleaner and more maintainable tests.
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
29
30
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", -1, 5, 4},}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 representing the test matrix, containing test names, inputs, and expected outcomes.
2
for _, tt := range tests
Iterates over each test case in the table, binding the current case to local scope variables.
3
t.Run(tt.name, func(t *testing.T) { ... })
Creates a subtest with its own reporting scope, making it easy to isolate and run specific test scenarios from the CLI.
4
t.Errorf(...)
Logs an assertion error if the output does not match expected value, but allows subsequent tests in the table to continue running.