Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go testing Package: Unit Tests, Table-Driven Tests, and Benchmarks

Table-driven subtests, t.Parallel ownership, benchmark timers and allocations, cleanup order, golden files, and fuzzing with property checks.

~5 min readGo
#Go#Testing#Best Practices
3D illustration of a tabular test matrix running cases with green check badges and benchmark stopwatches

The testing package defines three kinds of test entry points — TestXxx(t *testing.T), BenchmarkXxx(b *testing.B), and FuzzXxx(f *testing.F) — plus ExampleXxx functions verified through their output comments. Everything else in a test file is ordinary Go: table literals, subtests through t.Run, cleanup through t.Cleanup, and helpers that call t.Helper() so failures point at the caller.

Quick Summary

  • Test files end in _test.go and live in the same directory as the package; the package can be foo (internal) or foo_test (external, black box).
  • t.Run creates a subtest with its own name, failure state, and lifecycle; t.Parallel inside it runs it concurrently with other parallel subtests of the same parent.
  • t.Fatalf stops the current goroutine's test with runtime.Goexit; it must never be called from a goroutine the test did not create through t.Run.
  • t.Cleanup runs in LIFO order after the test, including after t.Fatal, which is why it is safer than defer in helpers.
  • Table-driven tests put the case name in the slice because it becomes the subtest name in go test -run 'TestX/name'.
  • Benchmarks measure b.N iterations chosen by the framework; work done outside the loop is measured unless b.ResetTimer is called, and results can be optimized away if nothing observes them.
  • b.ReportAllocs adds allocation counts, b.SetBytes adds throughput, and b.RunParallel measures a contended path.
  • The test cache keys on the source and command line; -count=1 defeats it, and -race is a different build so it never hits the normal cache.

Basic syntax and type signatures

go
package calc_test import ( "errors" "testing" ) func Add(a, b int) int { return a + b } func TestAdd(t *testing.T) { tests := []struct { name string a, b int want int }{ {"zero", 0, 0, 0}, {"positive", 2, 3, 5}, {"negative", -2, -3, -5}, {"mixed", -2, 3, 1}, } for _, tc := range tests { tc := tc // required before Go 1.22 when subtests run in parallel t.Run(tc.name, func(t *testing.T) { t.Parallel() if got := Add(tc.a, tc.b); got != tc.want { t.Fatalf("Add(%d, %d) = %d, want %d", tc.a, tc.b, got, tc.want) } }) } } func TestDivide(t *testing.T) { _, err := Divide(1, 0) if !errors.Is(err, ErrDivideByZero) { t.Fatalf("got %v, want %v", err, ErrDivideByZero) } }
go
func BenchmarkParse(b *testing.B) { input := []byte(`{"a":1,"b":[2,3]}`) b.ReportAllocs() b.SetBytes(int64(len(input))) b.ResetTimer() for i := 0; i < b.N; i++ { var v map[string]any if err := json.Unmarshal(input, &v); err != nil { b.Fatal(err) } sink = v } } var sink any // package-level: keeps the compiler from eliminating the work

Comparison of test entry points

Entry pointSignaturePurposeRuns with
TestXxxfunc(t *testing.T)pass/fail assertionsgo test
BenchmarkXxxfunc(b *testing.B)timing and allocationsgo test -bench .
FuzzXxxfunc(f *testing.F)randomized inputs, seed corpusgo test -fuzz FuzzXxx
ExampleXxxfunc() with // Output:executable documentationgo test
TestMainfunc(m *testing.M)suite-level setup and teardownonce per package

TestMain is the only one that does not take a *testing.T; it calls m.Run() and exits with its code, which is how a package sets up a database once for all tests:

go
func TestMain(m *testing.M) { setup() code := m.Run() teardown() os.Exit(code) }

Practical edge cases and deep dives

1. Subtests, parallelism, and what t.Parallel actually does

go
func TestCache(t *testing.T) { t.Run("hit", func(t *testing.T) { t.Parallel() c := NewCache() c.Set("k", "v") if got := c.Get("k"); got != "v" { t.Errorf("got %q", got) } }) t.Run("miss", func(t *testing.T) { t.Parallel() c := NewCache() if _, ok := c.Get("k"); ok { t.Error("expected miss") } }) }

A parallel subtest pauses at t.Parallel() and resumes after the parent returns, so all parallel children run at once and the parent waits for them. Two consequences follow. First, every parallel subtest must own its state — creating a Cache inside the subtest is correct, sharing one from the parent is a race. Second, the loop variable must be captured per iteration before Go 1.22; with the old semantics, tc := tc was required, and omitting it made every subtest run the last case. Go 1.22 changed for loop variables to be per-iteration, so the copy is now redundant but harmless and still common in older code.

t.Fatalf inside a goroutine that is not a subtest calls runtime.Goexit on that goroutine only, and the test continues, often to a nil-pointer panic on a value the failed call was supposed to fill. The fix is t.Errorf from goroutines (it is safe from any goroutine) and letting the parent decide, or creating a subtest for each goroutine.

2. Benchmarks: timers, allocations, and work that disappears

go
func BenchmarkConcat(b *testing.B) { parts := make([]string, 100) for i := range parts { parts[i] = "x" } b.Run("plus", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { s := "" for _, p := range parts { s += p } sink = s } }) b.Run("builder", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { var sb strings.Builder sb.Grow(len(parts)) for _, p := range parts { sb.WriteString(p) } sink = sb.String() } }) }

Three habits make a benchmark believable. Assign the result to a package-level variable, or the compiler is free to delete the work entirely and the benchmark reports nanoseconds for nothing. Call b.ReportAllocs() to see allocations per operation, which usually explains a performance difference better than the timing does. Call b.ResetTimer() after setup that is not part of what is being measured — building the input array is setup, and leaving it inside the timed loop inflates every result. b.N starts small and grows until the measurement is stable, so a benchmark that takes minutes for one operation is normal for the first run and cached after.

3. Cleanup, temp directories, and environment isolation

go
func TestWriteReport(t *testing.T) { dir := t.TempDir() // removed automatically after the test db := openTestDB(t) t.Cleanup(func() { db.Close() }) // runs after the test, LIFO t.Setenv("APP_MODE", "test") // restored automatically; incompatible with t.Parallel path := filepath.Join(dir, "out.txt") if err := WriteReport(path, "hello"); err != nil { t.Fatalf("WriteReport: %v", err) } b, err := os.ReadFile(path) if err != nil { t.Fatal(err) } if string(b) != "hello" { t.Fatalf("got %q", b) } } func openTestDB(t *testing.T) *sql.DB { t.Helper() // failures report the caller's line db, err := sql.Open("sqlite", ":memory:") if err != nil { t.Fatalf("open: %v", err) } return db }

t.Cleanup beats defer in helpers because the helper returns before the cleanup is needed, and because cleanups run even when the test ends with t.Fatal or t.Skip. t.TempDir removes its directory even on failure, which is the difference between a clean run and a full disk after a weekend of CI. t.Setenv cannot be combined with parallel tests — the environment is process-wide — and the framework panics with a clear message when it is.

4. Golden files with an update flag

go
var update = flag.Bool("update", false, "update golden files") func TestRender(t *testing.T) { got := Render(input()) golden := filepath.Join("testdata", "render.golden") if *update { if err := os.WriteFile(golden, []byte(got), 0o644); err != nil { t.Fatal(err) } return } want, err := os.ReadFile(golden) if err != nil { t.Fatalf("read golden: %v (run with -update to create)", err) } if got != string(want) { t.Errorf("output differs from %s\n--- got ---\n%s", golden, got) } }

The -update flag turns a failing comparison into a one-command regeneration of the expected output, and the diff belongs in code review rather than in the terminal — which is why golden files are committed and reviewed like source. A large golden file makes a real regression hard to spot, so keep one file per small unit of output, or compare structured data and format the diff.

5. Fuzzing and examples as tests

go
func FuzzUnmarshal(f *testing.F) { f.Add([]byte(`{"a":1}`)) f.Add([]byte(`[]`)) f.Add([]byte(``)) f.Fuzz(func(t *testing.T, data []byte) { var v map[string]any err := json.Unmarshal(data, &v) if err != nil { return // malformed input is a valid outcome } // The invariant: whatever parsed must re-marshal without error. if _, err := json.Marshal(v); err != nil { t.Fatalf("re-marshal failed for %q: %v", data, err) } }) } func ExampleAdd() { fmt.Println(Add(2, 3)) // Output: 5 }

Fuzzing finds the inputs nobody wrote in a table; the seed corpus is the table, and f.Fuzz asserts a property rather than an expected value. Example functions run as tests and fail when the output comment does not match, which makes them documentation that cannot rot — and go doc shows them next to the function they demonstrate.

Common mistakes and compiler errors

Error or symptomCauseFix
no tests to runfile not named _test.go, or function not TestXxxrename; the Xxx must not start lowercase
undefined: foo in an external testthe test is in package foo_test and uses an unexported identifiermove the test to package foo
Benchmark reports 0.3 ns/opthe work was optimized awayassign to a package-level variable
Timings include setupsetup inside the loopb.ResetTimer() after setup
t.Fatalf in a goroutine, test continuesruntime.Goexit only ends that goroutineuse t.Errorf, or a subtest
Parallel tests fail intermittentlyshared state between subtestsgive each subtest its own fixture
t.Setenv panicscalled from a parallel testdrop t.Parallel, or use per-test config
Tests pass locally, fail in CIthe local cache returned a stale result-count=1, and check -short paths
Race not reportedtests run without -raceadd -race to the test command
Golden file changes on every runmap iteration order or timestamps in the outputsort keys, inject a clock

The two habits that matter most are naming every subtest (the name is the only thing a CI failure tells you) and keeping the assertion message complete: Add(2, 3) = 6, want 5 is debuggable from a log, while want 5 requires opening the file. t.Helper() in every assertion helper keeps the reported line on the test rather than the helper, and t.Cleanup keeps teardown next to setup instead of at the top of the function where it is easy to forget.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.