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.

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.goand live in the same directory as the package; the package can befoo(internal) orfoo_test(external, black box). t.Runcreates a subtest with its own name, failure state, and lifecycle;t.Parallelinside it runs it concurrently with other parallel subtests of the same parent.t.Fatalfstops the current goroutine's test withruntime.Goexit; it must never be called from a goroutine the test did not create throught.Run.t.Cleanupruns in LIFO order after the test, including aftert.Fatal, which is why it is safer thandeferin 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.Niterations chosen by the framework; work done outside the loop is measured unlessb.ResetTimeris called, and results can be optimized away if nothing observes them. b.ReportAllocsadds allocation counts,b.SetBytesadds throughput, andb.RunParallelmeasures a contended path.- The test cache keys on the source and command line;
-count=1defeats it, and-raceis a different build so it never hits the normal cache.
Basic syntax and type signatures
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)
}
}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 workComparison of test entry points
| Entry point | Signature | Purpose | Runs with |
|---|---|---|---|
TestXxx | func(t *testing.T) | pass/fail assertions | go test |
BenchmarkXxx | func(b *testing.B) | timing and allocations | go test -bench . |
FuzzXxx | func(f *testing.F) | randomized inputs, seed corpus | go test -fuzz FuzzXxx |
ExampleXxx | func() with // Output: | executable documentation | go test |
TestMain | func(m *testing.M) | suite-level setup and teardown | once 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:
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
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
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
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
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
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 symptom | Cause | Fix |
|---|---|---|
no tests to run | file not named _test.go, or function not TestXxx | rename; the Xxx must not start lowercase |
undefined: foo in an external test | the test is in package foo_test and uses an unexported identifier | move the test to package foo |
| Benchmark reports 0.3 ns/op | the work was optimized away | assign to a package-level variable |
| Timings include setup | setup inside the loop | b.ResetTimer() after setup |
t.Fatalf in a goroutine, test continues | runtime.Goexit only ends that goroutine | use t.Errorf, or a subtest |
| Parallel tests fail intermittently | shared state between subtests | give each subtest its own fixture |
t.Setenv panics | called from a parallel test | drop t.Parallel, or use per-test config |
| Tests pass locally, fail in CI | the local cache returned a stale result | -count=1, and check -short paths |
| Race not reported | tests run without -race | add -race to the test command |
| Golden file changes on every run | map iteration order or timestamps in the output | sort 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.