Production Go · 9 min read · Intermediate
Table-Driven Tests & Benchmarks
Write idiomatic table-driven unit tests with testing.T and measure allocations with testing.B benchmarks.
What you'll learn
- Structure test cases as slices of structs (table-driven tests)
- Run targeted subtests with t.Run
- Detect data races with go test -race
Overview
Write idiomatic table-driven unit tests with testing.T and measure allocations with testing.B benchmarks.
Go prioritizes simplicity, explicit control flow, fast compilation, and safe concurrency. Every feature in this lesson is part of Go’s minimal standard toolkit used across cloud infrastructure, CLI tools, and high-throughput APIs.
Idiomatic Go Example
package mathutil
import "testing"
func TestAdd(t *testing.T) {
cases := []struct{ a, b, want int }{{2, 3, 5}, {-1, 1, 0}}
for _, tc := range cases {
if got := tc.a + tc.b; got != tc.want {
t.Fatalf("got %d, want %d", got, tc.want)
}
}
}
Key Takeaways
- Structure test cases as slices of structs (table-driven tests)
- Run targeted subtests with t.Run
- Detect data races with go test -race
Quick Check
Check Your Understanding
Score: 0 / 1
1. Which command runs Go unit tests with the built-in concurrency race detector enabled?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.