Organizing Go Tests
Write table-driven tests, name each case with t.Run subtests, and keep tests short with helpers and t.Cleanup.
Once you have more than a few tests, structure matters. This section covers the three habits that keep Go test files readable.
Table-Driven Tests
A slice of cases and one loop that checks them all.
tests := []struct{ name, input, want string }{ ... }
for _, tc := range tests { ... }
Subtests with t.Run
Each case gets a name, its own pass or fail, and can be run alone with -run 'TestSlug/empty'.
Test Helpers and Cleanup
t.Helper(), t.Cleanup, t.TempDir, t.Setenv and the testdata folder.
t.Setenv cannot be parallel:
Tests that change environment variables cannot call t.Parallel().
Summary
Tables for many inputs, subtests for names, helpers for setup.
Table-Driven Tests in Go
Write table-driven tests in Go - a slice of test cases looped over in one test function - with clear names, failure messages and error cases.
Subtests with t.Run in Go
Use t.Run to give each test case its own name and result, run a single subtest with -run, use Fatal safely inside cases, and run subtests in parallel.
Test Helpers, t.Helper and t.Cleanup in Go
Write reusable test helper functions with t.Helper for correct line numbers, clean up with t.Cleanup, and use t.TempDir, t.Setenv and testdata folders.