0 day streak
go / intermediate
Snippet

Implementing Table-Driven Tests in Go

Table-driven testing is a standard pattern in Go. It uses a slice of anonymous structs defining inputs and expected outputs to clean up test suites and run multiple assertions cleanly.

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 main
import "testing"
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -1, -1, -2},
{"mixed numbers", -5, 10, 5},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result := Add(tc.a, tc.b)
if result != tc.expected {
t.Errorf("Add(%d, %d) = %d; want %d", tc.a, tc.b, result, tc.expected)
}
})
}
}
Breakdown
1
tests := []struct {
Declares a slice of anonymous structs representing the test cases.
2
for _, tc := range tests {
Iterates over each test case in the defined table.
3
t.Run(tc.name, func(t *testing.T) {
Runs each test case as a subtest, providing isolated output and independent failure reporting.
4
t.Errorf("Add(%d, %d) = %d; want %d", tc.a, tc.b, result, tc.expected)
Logs the failure and marks the test as failed without stopping execution of remaining subtests.