Write Table-Driven Unit Tests in Go With testing.T and t.Run
Structure Go unit tests as a slice of cases, run named subtests with t.Run, and choose between t.Fatalf and t.Errorf. After this, adding edge cases to any Go function takes one line.
Skip ahead
Already writing table-driven tests with t.Run? Jump to Case 3: targeting one failing subtest with -run or Case 4: testing errors cleanly with wantErr.
Copy-pasting six near-identical test functions—TestClampNegative, TestClampZero, TestClampMax—creates bloated test files where adding one new edge case means duplicating 15 lines of setup. Go solves this idiomatically with table-driven tests: a slice of test-case structs executed inside named t.Run subtests.
Because each row gets its own subtest name, you get crisp failure output, can re-run a single failing case from the command line, and never need a third-party assertion framework. Verified on Go 1.27.
Case 1: Table-driven subtests with t.Run
Put the production code in clamp.go and the test right beside it in clamp_test.go (Go automatically excludes *_test.go from go build):
// mathutil/clamp.go
package mathutil
func Clamp(n, minVal, maxVal int) int {
if n < minVal {
return minVal
}
if n > maxVal {
return maxVal
}
return n
}
// mathutil/clamp_test.go
package mathutil
import "testing"
func TestClamp(t *testing.T) {
cases := []struct {
name string
in int
want int
}{
{name: "below_min", in: -5, want: 0},
{name: "at_min", in: 0, want: 0},
{name: "inside_range", in: 42, want: 42},
{name: "above_max", in: 150, want: 100},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := Clamp(tc.in, 0, 100)
if got != tc.want {
t.Fatalf("Clamp(%d, 0, 100) = %d, want %d", tc.in, got, tc.want)
}
})
}
}
$ go test -v ./...
=== RUN TestClamp
=== RUN TestClamp/below_min
=== RUN TestClamp/at_min
=== RUN TestClamp/inside_range
=== RUN TestClamp/above_max
--- PASS: TestClamp (0.00s)
PASS
ok example.com/demo/mathutil 0.002s
Case 2: Why t.Run beats a plain for loop
If you skip t.Run and write a bare for _, tc := range cases loop with t.Fatalf, the very first failing case aborts the entire loop—hiding whether the other 10 cases also failed! Wrapping each row in t.Run(tc.name, ...) isolates failures so every row still runs, prints the exact failing case name (FAIL: TestClamp/below_min), and lets you run subtests independently.
Case 3: Running one subtest, bypassing cache, and checking coverage
# Re-run only one subtest by regex:
$ go test -v -run TestClamp/above_max ./...
# Disable Go's passing-test result cache:
$ go test -count=1 ./...
# Check line coverage + race detector together:
$ go test -race -cover ./...
Case 4: Testing error paths cleanly in the same table
When a function returns (int, error) like parsePort(raw string), include a wantErr bool (or sentinel wantErr error checked with errors.Is) right in the struct:
cases := []struct {
name string
raw string
want int
wantErr bool
}{
{name: "valid", raw: "8080", want: 8080},
{name: "non_numeric", raw: "abc", wantErr: true},
{name: "too_high", raw: "70000", wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := parsePort(tc.raw)
if (err != nil) != tc.wantErr {
t.Fatalf("parsePort(%q) err = %v, wantErr=%v", tc.raw, err, tc.wantErr)
}
if !tc.wantErr && got != tc.want {
t.Fatalf("parsePort(%q) = %d, want %d", tc.raw, got, tc.want)
}
})
}
💡 Tip
Choose t.Fatalf when subsequent lines would panic (like reading fields after err != nil), and choose t.Errorf when checking multiple independent fields so you see every mismatch in one test run.
Common mistakes
- Misnaming the function without uppercase
Test:func testClamp(t *testing.T)compiles cleanly and is silently ignored bygo test. - Asserting exact error strings instead of
errors.IsorwantErr: Makes tests brittle whenever wording changes slightly. - Comparing slices or structs containing slices with
==: Slices are not comparable with==; useslices.Equal(got, want)orreflect.DeepEqual.
⚠ Warning
Put package-internal tests in package mathutil and external API tests in package mathutil_test. If you want to guarantee your exported functions work without peeking at private fields, use _test.
What happens if you skip this
Ad-hoc copy-pasted tests discourage adding boundary cases (zero, negative, empty string, max int), leaving off-by-one and validation bugs to surface in production.
Related course: Go for Beginners.
About
Structure Go unit tests as a slice of cases, run named subtests with t.Run, and choose between t.Fatalf and t.Errorf. After this, adding edge cases to any Go function takes one line.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.