Testing & Benchmarking: Table-Driven Tests, Subtests, Coverage, httptest
"Even after your test cases encounter a failure, they should keep going for as long as possible in order to print out all of the failed checks in a single run." — Go Wiki, "Go Test Comments" (supplement to Go Code Review Comments)
Summary: Go ships its test framework in the toolchain: go test finds TestXxx, BenchmarkXxx, FuzzXxx and ExampleXxx functions in _test.go files, builds one test binary per package, runs a vet subset first, and reports ok/FAIL. Everything else on this page (table-driven tests, subtests, parallelism, helpers, fixtures, golden files, httptest, benchmarks with b.Loop, benchstat, coverage, fuzzing, the race detector and fake time) is built from that small core. Focus: testing.T, t.Run and subtests, table-driven tests, t.Error vs t.Fatal, t.Parallel, t.Helper and testing.TB, t.Cleanup/t.TempDir/t.Setenv/t.Chdir/t.Context, TestMain and m.Run, -short and build tags, testdata and golden files, example tests, httptest.NewRecorder/NewRequest/NewServer, go-cmp and testify, testing.B with b.Loop and b.N, -benchmem, benchstat, profiles, -cover/-coverprofile/-covermode=atomic/GOCOVERDIR, testing.F fuzzing, -race, testing/synctest, flaky tests, and the go test flags you use daily (-run, -count, -failfast, -shuffle, -json). Learning goal: Write a test suite where every failure message says which input broke and what came back, that runs in parallel and in any order, needs no network or real clock unless it is an integration test, and measure performance changes with benchmarks and statistics instead of a single lucky run.
This page owns Go's testing package, the go test command, net/http/httptest, benchmarks, coverage and fuzzing. It does not re-teach its neighbours: designing code for testability with interfaces, fakes and mocks (testify mock, mockery, gomock) is in Mocking with Interfaces & DI; golangci-lint, Makefiles and CI layout are in Project Layout, golangci-lint & Build; the HTTP server and client themselves are in net/http; what a data race is and how the detector works inside is in Race Conditions & Deadlocks; t.Context() from the context side is in context; closures captured by subtests are in Functions & Closures; testing pipelines of goroutines is touched in Worker Pools & Pipelines; testing message consumers and contracts between services is in Testing Messaging Systems; designing classes for testability in general is in Low-Level Design.
Facts below were checked against the Go 1.27 sources on go.dev (testing/testing.go, benchmark.go, fuzz.go, allocs.go, testing/synctest, net/http/httptest; pkg.go.dev returns 403 to scripted fetches), go help test and go help testflag (in cmd/go/alldocs.go), the Go 1, 1.1, 1.2, 1.4, 1.7, 1.9, 1.10, 1.14, 1.15, 1.17, 1.18, 1.20–1.27 release notes, the Go blog posts on subtests, examples, the cover tool, integration-test coverage, fuzzing, B.Loop and synctest, the Go Wiki pages TableDrivenTests and TestComments, the go-cmp, testify, protocmp, test2json, gotestsum and benchstat sources, the Laravel 13 testing pages and PHPUnit's "Writing Tests", and Dave Cheney's "Prefer table driven tests". Snippets declare go 1.24 and pin github.com/google/go-cmp v0.7.0 (its go.mod at that tag says go 1.21) and github.com/stretchr/testify v1.12.1 (go 1.17 at that tag), both saved from the tagged go.mod files. One file uses testing/synctest behind a //go:build go1.25 tag. Everything was compiled, vetted and tested with -race on Go 1.27.4 (macOS, Apple M4 Pro); numbers in the lab are from that machine.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why Go has a built-in test tool and no framework | Why it exists |
| Which feature arrived in which Go version | Where it comes from |
| Copy-paste tests turned into one table | Go: before and after |
go test, testing.T, file and function names | go test and testing.T |
t.Error or t.Fatal? | t.Fatal vs t.Error |
Table-driven tests, t.Run, subtest names, -run | Table-driven tests and subtests |
t.Parallel, -parallel, loop variables | Parallel tests |
t.Helper, testing.TB | Helpers |
t.Cleanup, t.TempDir, t.Setenv, t.Chdir, t.Context | Fixtures that clean up |
TestMain, m.Run, package-wide setup | TestMain |
-short, //go:build integration | -short and build tags |
testdata, golden files, -update | Golden files |
ExampleXxx and // Output: | Example tests |
httptest.NewRecorder, NewRequest, NewServer, NewTestServer | httptest |
go-cmp, cmp.Diff, testify assert/require | Comparing values |
testing.B, b.Loop, b.N | Benchmarks |
b.ReportAllocs, b.ResetTimer, RunParallel, AllocsPerRun | Benchmark knobs |
benchstat, continuous benchmarking in CI | benchstat |
-cpuprofile, -memprofile, go tool pprof | Profiles from tests |
-cover, -coverprofile, -covermode, go tool cover | Coverage |
go build -cover, GOCOVERDIR, go tool covdata | Integration coverage |
testing.F, FuzzXxx, f.Add, corpus | Fuzzing |
-race in the test run | The race detector in tests |
Fake clocks, testing/synctest | Time in tests |
| Tests that pass and fail at random | Flaky tests |
| Every flag, the cache, the vet subset, exact output texts | Mechanics |
| The common test bugs and their fixes | Solving the classic problems |
| What to use when | Choosing |
| From one binary to many services | In architecture |
| Reproduce it on your machine | Lab |
| PHPUnit/Pest and Laravel HTTP tests compared | For PHP/Laravel developers |
Everything in one minute
The kinds of function go test looks for. All live in files ending in _test.go; the name prefix decides what they are.
| Function | Signature | Run by | What it proves | Since |
|---|---|---|---|---|
| Test | func TestXxx(t *testing.T) | every go test | Behaviour is correct | before Go 1 |
| Benchmark | func BenchmarkXxx(b *testing.B) | go test -bench regexp | How fast, how many allocations | before Go 1 |
| Example | func ExampleXxx() with // Output: | every go test (if it has an output comment) | Documentation still runs and prints this | — |
| Fuzz test | func FuzzXxx(f *testing.F) | seeds in every go test; mutation with -fuzz | No input breaks an invariant | Go 1.18 |
| Test main | func TestMain(m *testing.M) | instead of the tests, once per package | Package-wide setup and teardown | Go 1.4 |
"Before Go 1": the Go 1 release notes describe tests and benchmarks as already existing; "—" means the saved release notes do not date the API.
The testing.T methods you use every day.
| Method | Plain words | Since |
|---|---|---|
t.Error, t.Errorf | Record a failure, keep going | — |
t.Fatal, t.Fatalf | Record a failure, stop this test (runtime.Goexit) | — |
t.Run(name, f) | Start a named subtest | 1.7 |
t.Parallel() | Run me alongside other parallel tests | — |
t.Helper() | Report failures at my caller's line | 1.9 |
t.Cleanup(f) | Run f when the test and its subtests end, last added first | 1.14 |
t.TempDir() | A fresh directory, removed afterwards | 1.15 |
t.Setenv(k, v) | Set an env var, restore it afterwards (not in parallel tests) | 1.17 |
t.Skip, testing.Short() | Skip at run time, e.g. with -short | Skip 1.1 |
t.Context() | A context canceled just before cleanups run | 1.24 |
t.Chdir(dir) | Change directory, restore it afterwards (not in parallel tests) | 1.24 |
t.Attr(k, v) | Emit a key/value attribute into the test log | 1.25 |
t.ArtifactDir() | A directory for output files, kept with -artifacts | 1.26 |
The go test flags you use every day.
| Flag | Does | Example |
|---|---|---|
-run regexp | Run only matching tests, examples, fuzz seeds; / separates subtest levels | -run 'TestDiscount/half' |
-skip regexp | Skip matching ones (1.20) | -skip Integration |
-v | Print every test name and every t.Log | go test -v ./... |
-count n | Run each test n times; -count=1 bypasses the cache | -count=1 |
-race | Build with the race detector | go test -race ./... |
-short | Tell long tests to shorten themselves | -short in pre-commit |
-failfast | Do not start new tests after the first failure | local debugging |
-shuffle on | Randomise test order, print the seed (1.17) | -shuffle=on |
-json | Machine-readable events (via test2json) | CI reporters |
-bench regexp, -benchmem | Run benchmarks, print B/op and allocs/op | -bench . -benchmem |
-cover, -coverprofile f, -covermode m | Coverage summary, profile file, set/count/atomic | -coverprofile=c.out |
-fuzz regexp, -fuzztime t | Fuzz exactly one target for a while | -fuzz FuzzParse -fuzztime 30s |
-cpuprofile f, -memprofile f | Write pprof profiles | with -bench |
-timeout d | Panic if the binary runs longer (default 10m) | -timeout 2m |
-tags list | Build tags, e.g. for integration tests | -tags integration |
Why it exists
Most languages leave testing to a third-party framework with its own runner, assertion language, fixture system and plugins. Go chose the opposite: the test runner is part of the go command, a test is an ordinary function that receives a *testing.T, a failure is an ordinary if plus t.Errorf, and the same toolchain that builds your code also builds, vets, runs, caches, benchmarks, covers and fuzzes it. The consequence is that every Go project tests the same way: you can clone any repository and run go test ./... with no setup, and every CI system understands the output.
The cost is that the standard library gives you mechanisms, not conventions. Nothing forces you to write table-driven tests, readable failure messages, parallel-safe fixtures or statistically sound benchmarks. This page is about those conventions and the exact behaviour of the mechanisms underneath them.
| Framework-style testing (xUnit, PHPUnit, JUnit) | Go's built-in testing |
|---|---|
| Test classes, setUp/tearDown methods, annotations | Plain functions; t.Cleanup, TestMain, subtests |
Assertion DSL (assertEquals, matchers) | if got != want { t.Errorf(...) }, optionally cmp.Diff |
| Separate runner and config file | go test and flags |
| Data providers | Table-driven tests with t.Run |
| Plugins for coverage, benchmarks, fuzzing | -cover, -bench, -fuzz built in |
| Rich, familiar to newcomers | Small, uniform across every Go repository |
An everyday picture. A car inspection station. Each check is one line on a checklist (one row of a table-driven test); the inspector writes down every defect and keeps going (t.Error) unless the brakes do not work at all, in which case the road test is pointless (t.Fatal). Several inspection lanes work at once (t.Parallel), but the lift is shared, so only one car may be on it (t.Setenv is not allowed in parallel tests). The brake dynamometer is a fake road (httptest.NewServer): it lets the car believe it is driving without leaving the building. And the emissions test runs the engine at a fixed load for long enough to average out noise, ten times, before comparing it with last year's number (benchmarks with -count=10 and benchstat).
Three common misunderstandings, up front
- "A Go test should stop at the first failed assertion." The Go convention is the opposite: use
t.Errorso one run shows every broken check, andt.Fatalonly when continuing makes no sense. - "
go test ./...ran my tests." If nothing changed, it printed(cached)and ran nothing; and it never runs benchmarks unless you pass-bench, and never mutates fuzz inputs unless you pass-fuzz. - "One benchmark run tells me whether my change is faster." A single run is one sample of a noisy distribution. Run at least ten (
-count=10) before and after and letbenchstatdecide whether the difference is real.
Where it comes from
Tests and benchmarks are older than Go 1: the Go 1 release notes describe the testing package's existing type B "passed as an argument to benchmark functions", to which Go 1 added logging and failure methods "analogous to those of T". Go 1.1 added Skip to testing.T and testing.B "to simplify skipping an inappropriate test". Go 1.2 (2013) added test coverage: the release notes say go test "can now compute and, with help from a new, separately installed 'go tool cover' program, display test coverage results", and Rob Pike's blog post "The cover story" (2 December 2013) explains that it works by rewriting the source before compilation. Go 1.4 added TestMain. Go 1.7 (2016) added T.Run and B.Run; Marcel van Lohuizen's post "Using Subtests and Sub-benchmarks" (3 October 2016) introduced the slash-separated names that -run matches. Go 1.9 added t.Helper. Go 1.10 made go test cache successful results ("The idiomatic way to bypass test caching is to use -count=1") and run a high-confidence subset of go vet before every test.
The next wave was fixtures: Go 1.14 added T.Cleanup, Go 1.15 T.TempDir, Go 1.17 -shuffle and T.Setenv. Go 1.18 (2022) shipped native fuzzing, announced on the blog as beta in June 2021 by Katie Hockman and Jay Conrod. Go 1.20 made coverage work for whole programs: "build it with go build's -cover flag, then run the resulting binary with the environment variable GOCOVERDIR set", described in Than McIntosh's post "Code coverage for Go integration tests" (8 March 2023); it also added -skip. Go 1.22 gave each loop iteration its own variable, which ended the classic parallel-subtest capture bug.
The newest wave is about correctness of measurements and of concurrency tests. Go 1.24 (February 2025) added testing.B.Loop ("the faster and less error-prone" way to write benchmarks), T.Context, T.Chdir, the vet tests analyzer in the go test subset, and an experimental testing/synctest behind GOEXPERIMENT=synctest. Go 1.25 made testing/synctest generally available with synctest.Test, added T.Attr and T.Output, and made AllocsPerRun panic when parallel tests are running. Go 1.26 added T.ArtifactDir and the -artifacts flag, and stopped B.Loop from preventing inlining. Go 1.27 runs the stdversion vet check in go test, annotates -json output lines with OutputType, adds synctest.Sleep, and adds httptest.NewTestServer, which serves over an in-memory network.
Go
Before
A correct discount function with the test shape that does not scale: one copy-pasted function per case, t.Fatal everywhere, messages that do not name the input, and an error checked by its text.
// Package before computes an order discount. The code is fine; the tests
// next to it show the shape that does not scale.
package before
import (
"errors"
"strings"
)
// ErrUnknownCode is returned for a coupon code the shop does not know.
var ErrUnknownCode = errors.New("unknown coupon code")
// Discount returns the discount in cents for an order total in cents.
func Discount(totalCents int, code string) (int, error) {
switch strings.ToUpper(strings.TrimSpace(code)) {
case "":
return 0, nil
case "TENOFF":
if totalCents < 5000 {
return 0, nil
}
return 1000, nil
case "HALF":
return totalCents / 2, nil
default:
return 0, ErrUnknownCode
}
}package before
import "testing"
// One function per case, copy-pasted. Each stops at the first problem
// (t.Fatal), the message does not say which input failed, and the error is
// checked by its text.
func TestDiscountTenOff(t *testing.T) {
got, err := Discount(6000, "TENOFF")
if err != nil {
t.Fatal(err)
}
if got != 1000 {
t.Fatal("wrong discount")
}
}
func TestDiscountTenOffSmallOrder(t *testing.T) {
got, err := Discount(4000, "TENOFF")
if err != nil {
t.Fatal(err)
}
if got != 0 {
t.Fatal("wrong discount")
}
}
func TestDiscountHalf(t *testing.T) {
got, err := Discount(3000, "HALF")
if err != nil {
t.Fatal(err)
}
if got != 1500 {
t.Fatal("wrong discount")
}
}
func TestDiscountUnknown(t *testing.T) {
_, err := Discount(3000, "NOPE")
if err == nil || err.Error() != "unknown coupon code" {
t.Fatal("expected error")
}
}After
The same code, tested with one table: every case has a name that becomes a subtest, the cases run in parallel, errors are matched with errors.Is, and every message reads Discount(4999, "TENOFF") = ..., want .... Adding a case is one line; boundary cases (4999 and 5000) become obvious.
package after
import (
"errors"
"testing"
)
func TestDiscount(t *testing.T) {
t.Parallel() // this whole test may run alongside other parallel top-level tests
tests := []struct {
name string
total int
code string
want int
wantErr error
}{
{name: "no code", total: 6000, code: "", want: 0},
{name: "ten off at threshold", total: 5000, code: "TENOFF", want: 1000},
{name: "ten off below threshold", total: 4999, code: "TENOFF", want: 0},
{name: "code is case and space insensitive", total: 6000, code: " tenoff ", want: 1000},
{name: "half", total: 3001, code: "HALF", want: 1500},
{name: "unknown code", total: 3000, code: "NOPE", wantErr: ErrUnknownCode},
}
for _, tc := range tests { // Go 1.22+: tc is a fresh variable per iteration
t.Run(tc.name, func(t *testing.T) {
t.Parallel() // the cases run in parallel with each other
got, err := Discount(tc.total, tc.code)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("Discount(%d, %q) error = %v, want %v", tc.total, tc.code, err, tc.wantErr)
}
if got != tc.want {
t.Errorf("Discount(%d, %q) = %d, want %d", tc.total, tc.code, got, tc.want)
}
})
}
}The Go angle
Go treats tests as code, not configuration. A table is a slice literal, a matcher is an if, a fixture is a function that takes testing.TB and registers its own cleanup, a fake server is a real http.Server on a loopback port, and a benchmark is a loop. Because there is no framework, the tooling can see everything: the compiler type-checks tests, go vet checks them before they run (the tests and printf analyzers catch malformed names and wrong format verbs), the race detector instruments them, the coverage tool rewrites them, and the fuzzer instruments them for coverage guidance. The ecosystem adds small libraries rather than frameworks: github.com/google/go-cmp for diffs, github.com/stretchr/testify for assertions and mocks, golang.org/x/perf/cmd/benchstat for statistics, go.uber.org/goleak for goroutine leaks.
The concept catalogue
go test and testing.T Must-know
In plain words: Put a file named something_test.go next to your code, write func TestSomething(t *testing.T), and run go test. The test fails if it calls t.Error, t.Fatal or t.Fail, or panics; otherwise it passes.
Common misunderstanding: "Test files are a separate project." They are compiled with the package, so a test in package after can call unexported functions (white-box). A test in package after_test in the same directory sees only the exported API (black-box, "This is known as 'black box' testing" in the package doc). Both kinds can live side by side; the example test on this page uses after_test.
Definition: go test "recompiles each package along with any files with names matching the file pattern *_test.go" and "Each listed package causes the execution of a separate test binary". The test name must be TestXxx "where Xxx does not start with a lowercase letter". A directory named testdata is ignored by the go tool, "making it available to hold ancillary data needed by the tests". Tests run in the package's source directory, so relative paths like testdata/x.json work. In local directory mode (go test with no package) caching is off; in package list mode (go test ./..., even go test .) successful results are cached.
1 go test ./after package list mode
2 go build: after + *_test.go -> after.test (temporary)
3 go vet subset on the package and its tests (fails -> no run)
4 after.test -test.paniconexit0 -test.timeout=10m0s
5 TestDiscount ... ExampleDiscount ... Example_unordered
6 ok academy/testing-benchmarking/after 0.394s
7 second run, nothing changed -> ok ... (cached)Real scenario: a pre-commit hook that runs go test -short ./... in seconds; CI that runs go test -race -count=1 ./... on every push; a white-box test of an unexported parser; a black-box test that proves the public API is enough to use the package.
Package clause in _test.go | Sees | Use for |
|---|---|---|
package after | Exported and unexported identifiers | Unit tests of internals, test-only hooks |
package after_test | Exported API only (imports after) | Examples, API-level tests, avoiding import cycles |
package main tests | main's functions (not main itself as a process) | Testing helpers of a command; the process via GOCOVERDIR |
Fix / how to use it: keep tests next to the code, one _test.go per source file as a habit, and run go test ./... from the module root. The lifecycle of one run is drawn below; every box is unpacked in its own section.
t.Fatal vs t.Error Must-know
In plain words: t.Error says "this is wrong, keep checking"; t.Fatal says "this is wrong and nothing after it makes sense, stop this test now".
Common misunderstanding: "t.Fatal stops the whole test run." It stops the current test (or subtest) only: "Execution will continue at the next test or benchmark." Another one: calling t.Fatal from a goroutine you started. FailNow "must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test"; from another goroutine it does not stop the test and go vet's testinggoroutine analyzer reports it (that analyzer is in plain go vet, not in the subset go test runs).
Definition: "Error is equivalent to Log followed by Fail"; "Fatal is equivalent to Log followed by FailNow", and FailNow "marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine)". The Go Wiki: "prefer calling t.Error over t.Fatal", and "t.Fatal is usually only appropriate when some piece of test setup fails". Inside a subtest, "t.Fatal ends the current subtest and allows your test case to progress to the next subtest, so use t.Fatal."
test goroutine effect
1 got, err := Discount(4999, "TENOFF")
2 if err != nil { t.Fatalf(...) } stop: got is meaningless without a nil error
3 if got != 0 { t.Errorf(...) } record, continue
4 if len(log) != 1 { t.Errorf(...) } record, continue: one run shows both problems
5 return -> deferred calls, Cleanup, report FAIL with both messagesReal scenario: a JSON decode that fails (Fatal: every field check after it would panic on nil); a response with wrong status and wrong body (two Errors, so the developer sees both); a table row whose setup fails (Fatal inside t.Run ends only that row).
| Call | Marks failed | Stops the test | Safe from other goroutines |
|---|---|---|---|
t.Log | No | No | Yes |
t.Error, t.Errorf, t.Fail | Yes | No | Yes |
t.Fatal, t.Fatalf, t.FailNow | Yes | Yes (runtime.Goexit) | No: must be the test goroutine |
t.Skip, t.SkipNow | No (a failed test stays failed) | Yes | No |
panic | Yes, and the binary exits | Whole binary | Crashes everything |
Fix / how to use it: Fatal for setup and for errors that make later checks meaningless, Error for every independent property; in goroutines, send results back on a channel or call t.Error (safe) and let the test goroutine decide.
Table-driven tests and subtests (t.Run) Must-know
In plain words: Write the test logic once and feed it a list of cases. Wrap each case in t.Run(name, ...) so it gets its own name, its own pass/fail line and its own -run filter.
Common misunderstanding: "Table-driven tests are a library." The Go Wiki: "Table driven testing is not a tool, package or anything else, it's just a way and perspective to write cleaner tests." And "every case must go in the same table": the wiki also says that when cases need different checking logic, "it is more appropriate to write multiple test functions" (for example one table for valid inputs, one for errors).
Definition: a table is usually a slice of anonymous structs (name, inputs, want, wantErr), or a map keyed by name (Dave Cheney points out that map iteration order "is undefined", which shakes out order dependence). T.Run "runs f as a subtest of t called name. It runs f in a separate goroutine and blocks until f returns or calls t.Parallel". Names are joined with /; a name "is sanitized by replacing spaces with underscores and escaping non-printable characters" (subtests blog), and duplicates get "an optional trailing sequence number for disambiguation" (package doc). -run and -skip split their regexp on unbracketed / and match each level; parents of a match are always run.
TestDiscount -run pattern runs
1 t.Run("no code", ...) -> TestDiscount/no_code
2 t.Run("ten off at threshold") -> TestDiscount/ten_off_at_threshold 'Discount/ten_off' 2, 3
3 t.Run("ten off below ...") -> TestDiscount/ten_off_below_threshold
4 t.Run("half", ...) -> TestDiscount/half '/half' 4
5 t.Run("unknown code", ...) -> TestDiscount/unknown_code 'TestDiscount$' all 6Real scenario: validation rules for a signup form (twenty inputs, one assertion shape); a pricing engine with thresholds (test 4999, 5000, 5001); a URL router (method × path → handler); a parser of dates, money or durations; HTTP handler tests where each row is method, path, body, status (see httptest).
| Table shape | Advantage | Cost |
|---|---|---|
[]struct{ name string; ... } | Order is the reading order; duplicates allowed | Must remember to add a name |
map[string]struct{ ... } | Name is the key; random order exposes shared state | No stable order in output |
| Several tables per function | Each table has one checking logic | More functions |
| Subtests without a table | Shared setup, different logic per step | Less uniform |
t.Run inside b.Run style for benchmarks | Same names in -bench | See Benchmarks |
Fix / how to use it: follow the Go Wiki message format "YourFunc(%v) = %v, want %v" (identify the function, the input, got before want), use t.Fatalf only for the case's own setup, and pick names that read well after escaping. The After test is the template; the verbose run in the lab shows the names.
Parallel tests (t.Parallel) Must-know
In plain words: t.Parallel() says "this test does not share mutable state, run it at the same time as other tests that said the same". It pauses the test until all non-parallel tests at that level have finished, then resumes it alongside the others.
Common misunderstanding: "Packages run one after another, so parallel tests are pointless." Packages already run in parallel (-p), but inside one package the tests are sequential unless they opt in. The other one: "t.Parallel in a subtest makes the parent wait." It makes t.Run return immediately; the parent function returns, and the parent test completes only "once all of its subtests complete". Teardown that runs after the loop in the parent function therefore runs before the parallel subtests; put it in t.Cleanup or wrap the group in an extra t.Run.
Definition: Parallel "signals that this test is to be run in parallel with (and only with) other parallel tests, and pauses until all non-parallel tests have finished". -parallel n caps how many run at once, "By default, -parallel is set to the value of GOMAXPROCS", and "-parallel only applies within a single test binary". Since Go 1.22 the for _, tc := range tests variable is fresh per iteration, so the closure in each subtest sees its own tc (before 1.22 you needed tc := tc; the Go Wiki still shows that line as a comment "for Go < 1.22"). t.Setenv and t.Chdir panic in a parallel test or a test with a parallel ancestor.
main test goroutine parallel pool (-parallel 12)
1 TestA (sequential) runs to the end
2 TestDiscount: t.Parallel() -> paused
3 TestLoadEnv (sequential, uses t.Setenv) runs to the end
4 all sequential done ---------> TestDiscount resumes
5 TestDiscount/no_code ... /half ... in parallel
6 TestDiscount returns; its Cleanup runs after every subtest finishedReal scenario: a package with 400 table rows that drops from 6 s to 1 s; HTTP handler tests that each create their own httptest.Server; a test that accidentally shares one in-memory store between parallel subtests and fails one run in fifty; an -count=100 -race run that finds the shared state.
| Pattern | Parallel-safe? | Why |
|---|---|---|
| Each subtest builds its own fixture | Yes | No shared mutable state |
| Shared read-only table, read-only fixture | Yes | Reads only |
| Shared in-memory store that subtests write | No | Order and ids change; races |
t.Setenv, t.Chdir, os.Setenv | No (Setenv/Chdir panic) | Process-wide state |
| Global variable or package-level cache | No | Hidden shared state |
testing.AllocsPerRun | No (panics since 1.25) | Measures the whole process |
| Real database with per-test schema or transaction | Yes, with care | Isolation by schema or rollback |
Fix / how to use it: call t.Parallel() first thing in tests and subtests that are isolated, keep process-wide changes in non-parallel tests, run -race -count=… and -shuffle=on in CI to flush out sharing. The handler test on this page deliberately does not parallelise its subtests because one row creates an order that changes the ids the next rows expect.
Helpers: t.Helper and testing.TB Must-know
In plain words: A helper is a function that does test setup or a check and takes the *testing.T. Calling t.Helper() inside it makes failure messages point at the line in the test that called the helper, not at the helper's own t.Fatalf.
Common misunderstanding: "t.Helper is how you build my own assertion library." The Go Wiki: "t.Helper should not be used to implement assert libraries". It is for setup helpers and for checks whose failure message still names the function and input. Second one: "helpers must take *testing.T". Take testing.TB, the interface shared by *T, *B and *F, and the same helper works in tests, benchmarks and fuzz tests.
Definition: Helper "marks the calling function as a test helper function. When printing file and line information, that function will be skipped." It "may be called simultaneously from multiple goroutines". testing.TB contains Error, Fatal, Helper, Cleanup, TempDir, Setenv, Context, Chdir and the rest of the common methods; it has a private method, so only the testing package can implement it.
config_test.go
12 func writeConfig(tb testing.TB, body string) string {
13 tb.Helper()
17 tb.Fatalf("write config: %v", err) without Helper: "config_test.go:17: write config..."
...
24 path := writeConfig(t, "database_url=...") with Helper: "config_test.go:24: write config..."Real scenario: newTestDB(t) that opens a database and registers its close; mustReadFile(t, "testdata/x.json"); newRatesServer(t, handler) on this page that starts and registers the shutdown of a fake API; a helper shared by TestLoad and BenchmarkLoad.
| Helper style | Good | Bad |
|---|---|---|
newFixture(tb testing.TB) *Fixture + tb.Cleanup | Self-cleaning, reusable in benchmarks | None |
mustX(t, ...) calling t.Fatal on setup errors | Short tests | Do not hide the checked behaviour |
assertUserEqual(t, got, want) with cmp.Diff | One readable diff | Fine if it prints function and input |
A home-made assert.Equal DSL | Familiar | Wiki warns against it; messages lose context |
Fix / how to use it: the helpers snippet below shows a testing.TB helper used by a test and a benchmark.
package helpers
import (
"os"
"path/filepath"
"sync"
"testing"
"time"
)
// writeConfig is a helper usable from tests and benchmarks (testing.TB).
// t.Helper makes a failure point at the caller's line, not this one.
func writeConfig(tb testing.TB, body string) string {
tb.Helper()
dir := tb.TempDir() // removed automatically when the test ends
path := filepath.Join(dir, "app.conf")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
tb.Fatalf("write config: %v", err)
}
return path
}
func TestLoadFile(t *testing.T) {
t.Parallel()
path := writeConfig(t, "database_url=postgres://file\ntimeout=2s\n")
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load(%q): %v", path, err)
}
if cfg.DatabaseURL != "postgres://file" || cfg.Timeout != 2*time.Second {
t.Errorf("Load(%q) = %+v, want postgres://file and 2s", path, cfg)
}
}
// Not parallel: t.Setenv and t.Chdir change the whole process and panic
// in a test that called t.Parallel (or has a parallel ancestor).
func TestLoadEnvOverride(t *testing.T) {
t.Setenv("APP_DATABASE_URL", "postgres://env") // restored after the test
dir := t.TempDir()
t.Chdir(dir) // Go 1.24; restored after the test
if err := os.WriteFile("app.conf", []byte("database_url=postgres://file\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := Load("app.conf") // relative to the temporary directory
if err != nil {
t.Fatal(err)
}
if cfg.DatabaseURL != "postgres://env" {
t.Errorf("DatabaseURL = %q, want the environment value", cfg.DatabaseURL)
}
}
func TestLoadBadTimeout(t *testing.T) {
t.Parallel()
if _, err := Load(writeConfig(t, "timeout=soon\n")); err == nil {
t.Error("Load accepted timeout=soon, want an error")
}
}
func TestWatchStopsWithTestContext(t *testing.T) {
t.Parallel()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
Watch(t.Context(), time.Millisecond, func() {}) // Go 1.24: canceled when the test ends
}()
// t.Context is canceled just before Cleanup functions run, so this
// cleanup can wait for the goroutine: no leak into the next test.
t.Cleanup(wg.Wait)
}
func BenchmarkLoad(b *testing.B) {
path := writeConfig(b, "database_url=postgres://file\ntimeout=2s\n") // same helper, *testing.B
for b.Loop() {
if _, err := Load(path); err != nil {
b.Fatal(err)
}
}
}Fixtures that clean up: t.Cleanup, t.TempDir, t.Setenv, t.Chdir, t.Context Must-know
In plain words: Ask the test for the resources you need and let it undo them: a temporary directory, an environment variable, a working directory, a context, and any custom teardown with t.Cleanup.
Common misunderstanding: "defer is the same as t.Cleanup." A defer runs when the function that wrote it returns; a cleanup registered inside a helper runs when the test ends, which is what you want from newTestDB(t). And with parallel subtests the parent function returns before its subtests run, so a defer in the parent fires too early while t.Cleanup waits for "the test (or subtest) and all its subtests".
Definition: Cleanup "registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order." TempDir returns a directory "automatically removed when the test and all its subtests complete"; each call returns a new one, under GOTMPDIR if set. Setenv "calls os.Setenv and uses Cleanup to restore the environment variable to its original value after the test"; Chdir does the same for the working directory (and PWD on Unix); both "cannot be used in parallel tests or tests with parallel ancestors". Context "returns a context that is canceled just before Cleanup-registered functions are called", so "Cleanup functions can wait for any resources that shut down on context.Context.Done before the test or benchmark completes".
TestWatchStopsWithTestContext
1 go Watch(t.Context(), 1ms, reload) goroutine running
2 t.Cleanup(wg.Wait) registered
3 test function returns
4 t.Context() canceled ──────────────────▶ Watch sees ctx.Done(), returns, wg.Done()
5 Cleanup: wg.Wait() returns no goroutine leaks into the next test
6 TempDir removed, Setenv/Chdir restored (reverse order of registration)Real scenario: a config loader tested against a file in t.TempDir(); a feature flag read from APP_FEATURE_X set with t.Setenv; a CLI that reads ./config.yaml tested with t.Chdir(dir); a background poller started with t.Context() that must be stopped before the next test; a fake server closed with t.Cleanup(srv.Close).
| Need | Use | Restored by | Parallel? | Since |
|---|---|---|---|---|
| Any teardown | t.Cleanup(f) | LIFO after the test and subtests | Yes | 1.14 |
| Scratch files | t.TempDir() | Removed | Yes | 1.15 |
| Env var | t.Setenv(k, v) | Old value restored | No (panics) | 1.17 |
| Working directory | t.Chdir(dir) | Old directory restored | No (panics) | 1.24 |
| Stop goroutines at test end | t.Context() | Canceled before cleanups | Yes | 1.24 |
| Keep output files for CI | t.ArtifactDir() with -artifacts | Kept under -outputdir | Yes | 1.26 |
Fix / how to use it: never call os.Setenv/os.Chdir directly in tests, never write into the package directory except testdata on purpose (go help testflag: the test "must not write to it or any other directory within the module unless explicitly requested by the user"), and pair every goroutine a test starts with t.Context() plus a cleanup that waits. The code under test:
// Package helpers loads a small service configuration from a file and the
// environment. Its tests show t.Helper, testing.TB, t.Cleanup, t.TempDir,
// t.Setenv, t.Chdir and t.Context.
package helpers
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
)
// Config is the loaded configuration.
type Config struct {
DatabaseURL string
Timeout time.Duration
}
// Load reads key=value lines from path, then lets APP_DATABASE_URL in the
// environment override the file.
func Load(path string) (Config, error) {
f, err := os.Open(path)
if err != nil {
return Config{}, err
}
defer f.Close()
cfg := Config{Timeout: 5 * time.Second}
sc := bufio.NewScanner(f)
for sc.Scan() {
key, val, ok := strings.Cut(strings.TrimSpace(sc.Text()), "=")
if !ok {
continue
}
switch key {
case "database_url":
cfg.DatabaseURL = val
case "timeout":
d, err := time.ParseDuration(val)
if err != nil {
return Config{}, fmt.Errorf("timeout: %w", err)
}
cfg.Timeout = d
}
}
if err := sc.Err(); err != nil {
return Config{}, err
}
if v := os.Getenv("APP_DATABASE_URL"); v != "" {
cfg.DatabaseURL = v
}
return cfg, nil
}
// Watch calls reload every interval until ctx is canceled, then returns.
func Watch(ctx context.Context, interval time.Duration, reload func()) {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
reload()
}
}
}TestMain and m.Run Important
In plain words: If a test file defines func TestMain(m *testing.M), go test calls it instead of running the tests. You do setup, call m.Run() to run everything, do teardown, and exit with the code m.Run returned.
Common misunderstanding: "TestMain is where every test's setup goes." The package doc: "TestMain is a low-level primitive and should not be necessary for casual testing needs, where ordinary test functions suffice." Per-test fixtures belong in helpers with t.Cleanup; TestMain is for package-wide, expensive, shared things (a database container, a compiled binary, a large fixture). Second one: defer before os.Exit(code) does not run.
Definition: "TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run. m.Run will return an exit code that may be passed to os.Exit. If TestMain returns, the test wrapper will pass the result of m.Run to os.Exit itself." "When TestMain is called, flag.Parse has not been run": call flag.Parse() if setup reads flags (including testing.Short()). There is one TestMain per package test binary.
1 go test ./testmain
2 TestMain(m): flag.Parse(); build 50 000-row catalog (100 with -short)
3 code := m.Run() -> TestName, TestEveryProductHasAName (then fuzz seeds, examples, benchmarks with -bench)
4 os.RemoveAll(dir) explicit teardown (defers would be skipped by os.Exit)
5 os.Exit(code) 0 = ok, non-zero = FAILReal scenario: starting one PostgreSQL container for a whole package and giving each test its own schema; building the CLI binary once with go build -cover for integration tests; setting GOMAXPROCS or a global logger for the test binary; goleak.VerifyTestMain(m) to check for leaked goroutines after all tests.
| Task | TestMain | Per-test helper + Cleanup |
|---|---|---|
| Start a container once | Yes | No (too slow) |
| Per-test database schema or transaction | No | Yes |
Read custom flags (-update) | Not needed: flags are parsed before tests run | Yes |
| Global leak check | goleak.VerifyTestMain(m) | goleak.VerifyNone(t) |
| Skip everything without a dependency | os.Exit(0) with a message, or skip per test | Prefer t.Skip per test |
Fix / how to use it:
package testmain
import (
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// catalog is built once for every test in the package.
var catalog *Catalog
// TestMain runs in the main goroutine instead of the tests. It owns the
// expensive shared fixture: build it, run the tests, tear it down, exit.
func TestMain(m *testing.M) {
flag.Parse() // only needed because the setup below reads testing.Short()
dir, err := os.MkdirTemp("", "catalog-test-*")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
n := 50_000
if testing.Short() {
n = 100 // go test -short: a smaller fixture
}
var b strings.Builder
for i := range n {
fmt.Fprintf(&b, "SKU-%d;Product %d\n", i, i)
}
path := filepath.Join(dir, "catalog.txt")
if err := os.WriteFile(path, []byte(b.String()), 0o600); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if catalog, err = Open(path); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run() // tests, fuzz seeds, examples, then benchmarks with -bench
os.RemoveAll(dir) // os.Exit skips defers, so tear down explicitly
os.Exit(code)
}
func TestName(t *testing.T) {
t.Parallel()
if got, err := catalog.Name("SKU-7"); err != nil || got != "Product 7" {
t.Errorf(`Name("SKU-7") = %q, %v; want "Product 7", nil`, got, err)
}
if _, err := catalog.Name("SKU-unknown"); !errors.Is(err, ErrNoProduct) {
t.Errorf(`Name("SKU-unknown") error = %v, want ErrNoProduct`, err)
}
}
func TestEveryProductHasAName(t *testing.T) {
if testing.Short() {
t.Skip("walks the full catalog; skipped with -short")
}
for i := range catalog.Len() {
if _, err := catalog.Name(fmt.Sprintf("SKU-%d", i)); err != nil {
t.Fatalf("SKU-%d: %v", i, err)
}
}
}-short and build tags Important
In plain words: -short is a hint: tests that are slow check testing.Short() and skip or shrink themselves. Build tags are a hard switch: a file starting with //go:build integration is not even compiled unless you pass -tags integration.
Common misunderstanding: "-short skips slow tests automatically." It sets a flag and nothing else; each test decides. And "a build-tagged test file is checked by go vet ./...": without the tag it is invisible to the compiler, vet and the linters, so it rots unless CI builds it with -tags integration at least.
Definition: -short "Tell long-running tests to shorten their run time. It is off by default". testing.Short "reports whether the -test.short flag is set". A //go:build constraint line above the package clause includes the file only when the expression is true; tags come from -tags, GOOS/GOARCH, race (set by -race), and Go versions (go1.25 is true on Go 1.25 and later). A //go:build go1.N line also records the file's minimum Go version (Go 1.21 added go/ast.File.GoVersion for it); the synctest file on this page carries //go:build go1.25 so a Go 1.24 toolchain skips it while the module still says go 1.24.
1 go test ./... integration_test.go not compiled
2 go test -short ./... TestEveryProductHasAName: SKIP (walks the full catalog)
3 go test -tags integration ./testmain integration_test.go compiled
4 CATALOG_EXPORT unset TestCatalogFromRealExport: SKIP (set CATALOG_EXPORT ...)
5 CATALOG_EXPORT=/data/export.txt runs against the real fileReal scenario: a pre-commit go test -short ./... that finishes in two seconds; nightly go test -tags integration ./... against a staging database; //go:build race and //go:build !race files that switch an allocation assertion off under the race detector (used in the bench package); an e2e tag for tests that need a deployed environment.
| Mechanism | Granularity | Compiled without it? | Typical use |
|---|---|---|---|
testing.Short() + t.Skip | Per test, at run time | Yes | Slow but self-contained tests |
//go:build integration | Per file, at build time | No | Needs a database, network, credentials |
Env var check + t.Skip | Per test, at run time | Yes | Optional external dependency |
-run/-skip regexp | Per name | Yes | Ad-hoc selection |
//go:build race | Per file | No | Race-specific constants |
Fix / how to use it:
//go:build integration
// Compiled only with: go test -tags integration ./testmain
// The default go test ./... never sees this file.
package testmain
import (
"os"
"testing"
)
func TestCatalogFromRealExport(t *testing.T) {
path := os.Getenv("CATALOG_EXPORT")
if path == "" {
t.Skip("set CATALOG_EXPORT to a real export file to run this test")
}
c, err := Open(path)
if err != nil {
t.Fatalf("Open(%q): %v", path, err)
}
if c.Len() == 0 {
t.Errorf("export %q has no products", path)
}
}testdata and golden files (-update flag) Important
In plain words: A golden file holds the exact output your code is expected to produce (a report, an HTML page, generated code). The test renders the output and compares it byte-for-byte with the file in testdata; when the output is meant to change, you rerun with -update and review the diff.
Common misunderstanding: "-update is a go test flag." It is a flag your test package defines with flag.Bool("update", ...); the go command passes unknown flags through to the test binary. Second one: golden files for JSON produced by encoding/json. The Go Wiki warns that json.Marshal "makes no guarantee about the exact bytes that it may emit"; compare semantically (decode then cmp.Diff) unless you own the formatting.
Definition: the go tool ignores directories named testdata, so fixtures there are not packages; tests run in the package directory, so filepath.Join("testdata", t.Name()+".golden") finds them. The -update pattern: if the flag is set, write the current output to the golden file, then read the file and compare. A golden file is a reviewed snapshot; the review happens in the version-control diff.
1 go test ./golden render -> compare with testdata/TestRender.golden -> ok
2 change Render (new column) go test ./golden -> FAIL: Render() mismatch --- got ... --- want
3 go test ./golden -update file rewritten with the new output
4 git diff testdata/ reviewer checks the new column is intended
5 commit code + golden file togetherReal scenario: a CLI's --help text; generated SQL migrations; an invoice PDF's text layer; an html/template page; protobuf/codegen output; error messages users see.
| Comparison | Fits | Breaks when |
|---|---|---|
| Golden file, bytes | Output you format yourself | Unstable order (maps), timestamps |
| Golden file, normalised | Output with ids/timestamps | You forget a field to normalise |
Decode then cmp.Diff | JSON, YAML from libraries | Never on formatting changes |
Inline want string | Short outputs | Long outputs become unreadable |
Fix / how to use it:
package golden
import (
"bytes"
"flag"
"os"
"path/filepath"
"testing"
)
// go test ./golden -update rewrites the golden file; review the diff in
// version control before committing it.
var update = flag.Bool("update", false, "rewrite testdata/*.golden files")
func TestRender(t *testing.T) {
var buf bytes.Buffer
err := Render(&buf, "2026-11-28", []Line{
{SKU: "MUG-01", Units: 3, Cents: 4497},
{SKU: "BOOK-7", Units: 1, Cents: 2950},
{SKU: "PEN-22", Units: 12, Cents: 1188},
})
if err != nil {
t.Fatal(err)
}
golden := filepath.Join("testdata", t.Name()+".golden") // go test runs in the package directory
if *update {
if err := os.WriteFile(golden, buf.Bytes(), 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("read golden file (run with -update to create it): %v", err)
}
if !bytes.Equal(buf.Bytes(), want) {
t.Errorf("Render() mismatch\n--- got\n%s\n--- want (%s)\n%s", buf.Bytes(), golden, want)
}
}Example tests (ExampleXxx, Output:) Important
In plain words: An example is a function named ExampleXxx that prints something and ends with a // Output: comment. go test runs it and fails if the printed text differs; go doc and pkg.go.dev show it as documentation for Xxx.
Common misunderstanding: "Examples without an output comment are tested." They are only compiled: "Example functions without output comments are compiled but not executed." And "the comparison is exact to the byte": it "ignores leading and trailing space"; // Unordered output: ignores line order.
Definition: names attach the example to an identifier: Example() (package), ExampleF, ExampleT, ExampleT_M, plus a lower-case suffix for more than one (ExampleF_second). Andrew Gerrand's post "Testable Examples in Go" (7 May 2015) describes them as snippets "displayed as package documentation and that are verified by running them as tests". -count does not repeat them ("Examples are always run once").
1 func ExampleDiscount() { fmt.Println(after.Discount(6000, "TENOFF")) ... // Output: 1000 <nil> ... }
2 go test -run Example -v ./after
3 --- PASS: ExampleDiscount (0.00s)
4 change Discount to return 900 -> --- FAIL: ExampleDiscount got: 900 <nil> want: 1000 <nil>Real scenario: a library's README usage that can never go stale; documenting the error a function returns; showing map output with Unordered output; a "whole file" example (one example function plus helper types, no tests) shown as a full program.
| Comment | Behaviour |
|---|---|
// Output: x | Run; stdout must equal x (trimmed) |
// Output: with nothing after | Run; must print nothing |
// Unordered output: | Run; same lines in any order |
| None | Compiled only |
Fix / how to use it:
package after_test
import (
"fmt"
"academy/testing-benchmarking/after"
)
// ExampleDiscount is compiled, run by go test, compared with the Output
// comment, and shown in the package documentation under Discount.
func ExampleDiscount() {
d, err := after.Discount(6000, "TENOFF")
fmt.Println(d, err)
_, err = after.Discount(6000, "NOPE")
fmt.Println(err)
// Output:
// 1000 <nil>
// unknown coupon code
}
// Example_unordered shows the "Unordered output" form for output whose
// line order is not fixed, such as map iteration.
func Example_unordered() {
codes := map[string]int{"TENOFF": 6000, "HALF": 3000}
for code, total := range codes {
d, _ := after.Discount(total, code)
fmt.Println(code, d)
}
// Unordered output:
// HALF 1500
// TENOFF 1000
}httptest: NewRecorder, NewRequest, NewServer Must-know
In plain words: To test a handler, build a fake incoming request with httptest.NewRequest, a fake response writer with httptest.NewRecorder, call handler.ServeHTTP(rec, req) and inspect what was written. To test a client, start a fake server with httptest.NewServer(handler) and point the client at its URL.
Common misunderstanding: "rec.Code is the status the client sees." If the handler never calls WriteHeader or Write, Code "might end up being 0, rather than the implicit http.StatusOK. To get the implicit value, use the Result method." Read status and headers from rec.Result(). Second one: "httptest.NewRequest gives me a request for http.Client.Do." It builds an incoming server request ("To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package").
Definition: NewRequest "wraps NewRequestWithContext using context.Background"; the target "may be either a path or an absolute URL", the host defaults to example.com, Proto is always HTTP/1.1, it "panics on error for ease of use in testing", and RemoteAddr is 192.0.2.1:1234 (TEST-NET). NewRecorder returns a ResponseRecorder whose Body is a bytes.Buffer and whose Result() returns an *http.Response. NewServer "starts and returns a new Server listening on a local network loopback interface"; "The caller should call Server.Close when finished", and Close "blocks until all outstanding requests on this server have completed". srv.Client() is configured for the server (including TLS for NewTLSServer). Go 1.27 adds NewTestServer(t, handler), which uses "an in-memory network implementation by default", registers its own cleanup, fails the test if the handler panics, and is "suitable for use with the testing/synctest package"; its doc says "Most users should use NewTestServer instead". The snippets on this page use NewServer because they target Go 1.24.
handler test (no network) client test (loopback server)
1 req := httptest.NewRequest(GET, "/orders/1", nil) srv := httptest.NewServer(fakeAPI); t.Cleanup(srv.Close)
2 rec := httptest.NewRecorder() c := &RatesClient{BaseURL: srv.URL, HTTP: srv.Client()}
3 h.ServeHTTP(rec, req) c.Rate(ctx, "EUR", "USD") -> GET http://127.0.0.1:PORT/rates?...
4 res := rec.Result(); res.StatusCode fakeAPI checks the query, writes {"rate":1.08}
5 rec.Body.String() assert the decoded value; Close waits for the handlerReal scenario: status codes and JSON for every route of an API in a table; middleware tests (headers added, 401 without a token; see Middlewares); a payment-provider client tested against a fake that returns 502, slow responses and malformed JSON; a webhook sender whose fake receiver records the payload.
| Tool | Tests | Network | Speed | Since |
|---|---|---|---|---|
NewRequest + NewRecorder + ServeHTTP | One handler or the mux | None | Microseconds | NewRequest, Result 1.7 |
httptest.NewRequestWithContext | Handler with a ctx (deadline, values) | None | Microseconds | 1.23 |
NewServer + srv.Client() | Clients, full stack, middleware | Loopback TCP | Milliseconds | Server.Client 1.9 |
NewTLSServer | Clients over HTTPS | Loopback TLS | Milliseconds | — |
NewUnstartedServer + Start | Server config changes before start | Loopback | Milliseconds | — |
NewTestServer(t, h) | Same, auto cleanup, panic check, synctest | In-memory | Faster, no ports | 1.27 |
Fix / how to use it: the handler test runs the whole route table through ServeHTTP, then one test runs over a real server; the client tests fake the external API, including a timeout that must surface as context.DeadlineExceeded (see context). The handlers themselves are explained in net/http.
package httpapi
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Handler tests call ServeHTTP directly: no listener, no port, microseconds.
func TestHandler(t *testing.T) {
t.Parallel()
store := NewMemStore()
seeded, _ := store.Create(Order{SKU: "MUG-01", Units: 2})
h := NewHandler(store)
tests := []struct {
name string
method string
target string
body string
wantCode int
wantBody string // substring
}{
{"get existing", http.MethodGet, "/orders/1", "", http.StatusOK, `"sku":"MUG-01"`},
{"get missing", http.MethodGet, "/orders/99", "", http.StatusNotFound, "order not found"},
{"get bad id", http.MethodGet, "/orders/abc", "", http.StatusBadRequest, "bad id"},
{"create", http.MethodPost, "/orders", `{"sku":"PEN-22","units":3}`, http.StatusCreated, `"id":2`},
{"create invalid", http.MethodPost, "/orders", `{"sku":""}`, http.StatusUnprocessableEntity, "invalid order"},
{"wrong method", http.MethodDelete, "/orders/1", "", http.StatusMethodNotAllowed, ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Not parallel: "create" changes the shared store and the ids.
req := httptest.NewRequest(tc.method, tc.target, strings.NewReader(tc.body))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
res := rec.Result()
if res.StatusCode != tc.wantCode {
t.Fatalf("%s %s: status = %d, want %d (body %q)", tc.method, tc.target, res.StatusCode, tc.wantCode, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), tc.wantBody) {
t.Errorf("%s %s: body = %q, want it to contain %q", tc.method, tc.target, rec.Body.String(), tc.wantBody)
}
})
}
// The JSON body of the seeded order, decoded and compared as a whole.
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/orders/1", nil))
var got Order
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatal(err)
}
if got != seeded {
t.Errorf("GET /orders/1 = %+v, want %+v", got, seeded)
}
}
// The same handler behind a real server, to exercise the full stack
// (routing, headers, the client) over loopback.
func TestHandlerOverHTTP(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(NewHandler(NewMemStore()))
t.Cleanup(srv.Close)
res, err := srv.Client().Post(srv.URL+"/orders", "application/json", strings.NewReader(`{"sku":"BOOK-7","units":1}`))
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated || res.Header.Get("Location") != "/orders/1" {
t.Errorf("POST /orders: status %d, Location %q; want 201 and /orders/1", res.StatusCode, res.Header.Get("Location"))
}
}package httpapi
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// newRatesServer fakes the external API. The handler can also assert on
// the request the client sent.
func newRatesServer(t *testing.T, h http.HandlerFunc) *RatesClient {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close) // Close blocks until outstanding requests finish
return &RatesClient{BaseURL: srv.URL, HTTP: srv.Client()}
}
func TestRate(t *testing.T) {
t.Parallel()
c := newRatesServer(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("from"); got != "EUR" {
t.Errorf("from = %q, want EUR", got) // t.Errorf is safe from the server goroutine
}
w.Write([]byte(`{"rate":1.08}`))
})
got, err := c.Rate(t.Context(), "EUR", "USD")
if err != nil || got != 1.08 {
t.Errorf("Rate(EUR, USD) = %v, %v; want 1.08, nil", got, err)
}
}
func TestRateServerError(t *testing.T) {
t.Parallel()
c := newRatesServer(t, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusBadGateway)
})
if _, err := c.Rate(t.Context(), "EUR", "USD"); err == nil {
t.Error("Rate on a 502 returned nil error")
}
}
func TestRateTimeout(t *testing.T) {
t.Parallel()
serverSawCancel := make(chan struct{})
c := newRatesServer(t, func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // a slow upstream that never answers in time
close(serverSawCancel)
})
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
_, err := c.Rate(ctx, "EUR", "USD")
// Assert behaviour, not elapsed time: the error is the deadline, and the
// cancellation reached the server. No "took less than X" check, which a
// loaded CI machine can break.
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Rate with a 20ms budget: err = %v, want DeadlineExceeded", err)
}
select {
case <-serverSawCancel:
case <-time.After(10 * time.Second): // generous safety net, not a performance claim
t.Fatal("server handler never saw the client's cancellation")
}
}Comparing values: go-cmp, cmp.Diff, assertion libraries, testify require vs assert Important
In plain words: For anything bigger than a number, build the whole expected value and compare it in one shot. cmp.Diff(want, got) from github.com/google/go-cmp returns an empty string when they are equal and a readable -want +got diff when not. Assertion libraries such as testify give you assert.Equal(t, want, got) instead of the if.
Common misunderstanding: "reflect.DeepEqual is the standard way." The Go Wiki: "Prefer cmp for new code", because reflect.DeepEqual "is sensitive to changes in unexported fields and other implementation details" and gives no diff. And "testify assert stops the test". It does not: "The require package provides same global functions as the assert package, but instead of returning a boolean result they terminate current test." So assert is t.Errorf, require is t.FailNow.
Definition: cmp.Diff "returns a human-readable report of the differences between two values: y - x. It returns an empty string if and only if Equal returns true"; - lines are from the first argument, + from the second, hence the Wiki's advice to write "diff -want +got" when calling cmp.Diff(want, got). Unlike DeepEqual, unexported fields "result in panics unless suppressed by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared using the AllowUnexported option". Options from cmpopts (signatures in cmp/cmpopts): IgnoreFields(typ any, names ...string), IgnoreUnexported, EquateEmpty(), EquateApprox(fraction, margin float64), EquateApproxTime, SortSlices(lessOrCompareFunc any). The Go Wiki's position on assertion libraries: "Avoid the use of 'assert' libraries"; many teams use testify anyway, and its assert/require split maps exactly onto Error/Fatal.
cmp.Diff(want, got, cmpopts.IgnoreFields(Profile{}, "CreatedAt"))
1 want: {Email: "alice@example.test", Name: "Alice", Roles: [customer]}
2 got: {Email: "alice@example.test", Name: "Alice ", Roles: [customer], CreatedAt: 14:50:00}
3 diff (-want +got):
compare.Profile{
Email: "alice@example.test",
- Name: "Alice",
+ Name: "Alice ",
...
}Real scenario: comparing a decoded API response struct while ignoring generated ids and timestamps; comparing slices whose order does not matter with cmpopts.SortSlices; protobuf messages with cmp.Comparer(proto.Equal) (the Go Wiki's advice) or protocmp.Transform() from google.golang.org/protobuf/testing/protocmp; a team migrating from PHPUnit that standardises on testify require for setup and assert for checks.
| Approach | Failure output | Stops the test | Dependency |
|---|---|---|---|
if got != want { t.Errorf(...) } | What you write | No | None |
reflect.DeepEqual + %+v | Two dumps, find the difference yourself | No | None |
cmp.Diff / cmp.Equal | -want +got diff | No | github.com/google/go-cmp |
testify assert.Equal | Expected/actual + diff | No (t.Errorf) | github.com/stretchr/testify |
testify require.Equal, require.NoError | Same | Yes (t.FailNow) | github.com/stretchr/testify |
testify suite | Setup/teardown methods | n/a | README: "does not support parallel tests" |
Fix / how to use it: the code under test returns a struct with a timestamp; the test ignores that field in the diff and checks it separately, then shows testify's two packages side by side. Mocks from testify are a different subject: see Mocking with Interfaces & DI.
package compare
import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// go-cmp: compare the whole struct, ignore the field that is not
// deterministic, print a readable diff with a direction key.
func TestSignupCmp(t *testing.T) {
t.Parallel()
got, err := Signup(" Alice@Example.TEST ", " Alice ")
if err != nil {
t.Fatalf("Signup: %v", err)
}
want := Profile{Email: "alice@example.test", Name: "Alice", Roles: []string{"customer"}}
if diff := cmp.Diff(want, got, cmpopts.IgnoreFields(Profile{}, "CreatedAt")); diff != "" {
t.Errorf("Signup() mismatch (-want +got):\n%s", diff)
}
if got.CreatedAt.IsZero() {
t.Error("CreatedAt is zero, want it set")
}
}
// testify: require stops the test (t.FailNow) when a precondition fails;
// assert records the failure (t.Errorf) and keeps going.
func TestSignupTestify(t *testing.T) {
t.Parallel()
got, err := Signup("bob@example.test", "Bob")
require.NoError(t, err) // nothing below makes sense without a profile
assert.Equal(t, "bob@example.test", got.Email)
assert.Equal(t, "Bob", got.Name)
assert.Equal(t, []string{"customer"}, got.Roles)
assert.WithinDuration(t, time.Now(), got.CreatedAt, time.Minute)
_, err = Signup("not-an-email", "X")
assert.ErrorIs(t, err, ErrInvalidEmail)
}Benchmarks: testing.B, b.Loop, b.N Must-know
In plain words: A benchmark is a function BenchmarkXxx(b *testing.B) with a loop around the code you want to time. Since Go 1.24 the loop is for b.Loop() { ... }: the framework decides how many iterations are needed for a stable number (one second by default) and reports nanoseconds per iteration.
Common misunderstanding: "My b.N benchmark runs the function body once." The old style calls the whole benchmark function several times with growing b.N ("This also means any setup done before the loop may be run several times"), and without a sink the compiler may delete the call: the B.Loop blog shows a benchmark that "doesn't measure isCond at all; it measures how long it takes to do nothing". Second: "benchmarks run in go test". "By default, no benchmarks are run"; you need -bench.
Definition: Loop "returns true as long as the benchmark should continue running"; it "resets the benchmark timer the first time it is called", stops it when it returns false, and inside "for b.Loop() { ... }" "arguments to and results from function calls and assigned variables within the loop are kept alive, preventing the compiler from fully optimizing away the loop body". "After Loop returns false, b.N contains the total number of iterations". "Benchmarks should either use Loop or contain a loop to b.N, but not both." The Go 1.24 notes: the benchmark function "will execute exactly once per -count". Go 1.26: B.Loop "no longer prevents inlining in the loop body". Output format: BenchmarkRandInt-8 68453040 17.8 ns/op "means that the body of the loop ran 68453040 times at a speed of 17.8 ns per loop"; the -8 suffix is GOMAXPROCS. "Benchmarks are run sequentially."
b.N style (function called per round) b.Loop style (function called once)
1 round 1: setup; ResetTimer; N=1 setup (untimed)
2 round 2: setup; ResetTimer; N=100 Loop(): timer reset, ramp 1, 100, 10 000 ...
3 round 3: setup; ResetTimer; N=10 000 ... body kept alive, no sink needed
4 until the timed part >= -benchtime (1s) Loop() == false: timer stopped, b.N = total
5 report ns/op = elapsed / N report ns/op = elapsed / b.NReal scenario: choosing between += and strings.Builder in a hot path (the lab shows 735 µs vs 4.8 µs at 1000 items); measuring a JSON encoder per payload size with sub-benchmarks; proving a cache lookup does not allocate; checking a regex compiled once versus per call.
| Benchmark style | Setup repeated | Dead-code risk | Timer handling | Use |
|---|---|---|---|---|
for b.Loop() { ... } | No | Low (kept alive) | Automatic | All new benchmarks (Go 1.24+) |
for range b.N { ... } / for i := 0; i < b.N; i++ | Yes, per round | High without a sink | b.ResetTimer, b.StopTimer by hand | Existing code, Go before 1.24 |
b.Run(name, ...) sub-benchmarks | Per sub-benchmark | As above | Per sub-benchmark | Sizes, variants (plus/n=100) |
b.RunParallel(func(pb) { for pb.Next() ... }) | Per goroutine | As above | Do not touch the timer | Contention, throughput |
Fix / how to use it:
package bench
import (
"fmt"
"testing"
)
var sizes = []int{10, 100, 1000}
// Go 1.24+ style: setup before the loop is not timed, the loop body is
// kept alive, and the function body runs once per -count.
func BenchmarkJoin(b *testing.B) {
for _, n := range sizes {
items := Items(n)
b.Run(fmt.Sprintf("plus/n=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
JoinPlus(items)
}
})
b.Run(fmt.Sprintf("builder/n=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
JoinBuilder(items)
}
})
}
}
// sink keeps the b.N-style result alive so the compiler cannot drop the call.
var sink string
// The pre-1.24 b.N style, still everywhere in existing code: the function
// is called several times with growing b.N, so expensive setup must be
// excluded with b.ResetTimer.
func BenchmarkJoinBuilderN(b *testing.B) {
items := Items(1000) // setup
b.ResetTimer()
for i := 0; i < b.N; i++ {
sink = JoinBuilder(items)
}
}
// RunParallel spreads b.N iterations over GOMAXPROCS goroutines; ns/op is
// wall time for the whole benchmark.
func BenchmarkJoinBuilderParallel(b *testing.B) {
items := Items(100)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_ = JoinBuilder(items)
}
})
}
// ReportMetric adds a custom unit next to ns/op.
func BenchmarkJoinBytes(b *testing.B) {
items := Items(100)
var total int
for b.Loop() {
total += len(JoinBuilder(items))
}
b.ReportMetric(float64(total)/float64(b.N), "bytes/op")
}
// An allocation budget as a normal test: fails the build when someone adds
// an allocation to the hot path. Not parallel: AllocsPerRun panics while
// parallel tests run (Go 1.25).
func TestJoinBuilderAllocs(t *testing.T) {
if raceEnabled {
t.Skip("allocation counts are not meaningful under -race")
}
items := Items(100)
allocs := testing.AllocsPerRun(100, func() { sink = JoinBuilder(items) })
if allocs != 1 {
t.Errorf("JoinBuilder allocs = %v, want 1", allocs)
}
}
func TestJoinSame(t *testing.T) {
t.Parallel()
for _, n := range []int{0, 1, 2, 50} {
items := Items(n)
if p, s := JoinPlus(items), JoinBuilder(items); p != s {
t.Errorf("n=%d: JoinPlus = %q, JoinBuilder = %q", n, p, s)
}
}
}Benchmark knobs: b.ReportAllocs, b.ResetTimer, -benchmem, RunParallel, ReportMetric, testing.AllocsPerRun Important
In plain words: Benchmarks report time by default. -benchmem (or b.ReportAllocs() in one benchmark) adds bytes and allocations per operation; b.ResetTimer/StopTimer/StartTimer exclude parts from the timing in b.N style; b.ReportMetric adds your own unit; testing.AllocsPerRun turns an allocation count into a normal test assertion.
Common misunderstanding: "RunParallel reports the time per goroutine." It "reports ns/op values as wall time for the benchmark as a whole, not the sum of wall time or CPU time over each parallel goroutine". And "AllocsPerRun works anywhere": it "sets runtime.GOMAXPROCS to 1 during its measurement", and since Go 1.25 it "now panics if parallel tests are running" because the result "is inherently flaky if other tests are running". Under -race the counts change too, which is why the snippet skips that test with a race build tag.
Definition: ReportAllocs "enables malloc statistics for this benchmark. It is equivalent to setting -test.benchmem, but it only affects the benchmark function that calls ReportAllocs." ResetTimer "zeroes the elapsed benchmark time and memory allocation counters and deletes user-reported metrics. It does not affect whether the timer is running." ReportMetric "adds 'n unit' to the reported benchmark results. If the metric is per-iteration, the caller should divide by b.N, and by convention units should end in '/op'." SetBytes makes the output include MB/s. -benchtime 2s or -benchtime 100x changes the target; -cpu 1,2,4 repeats with different GOMAXPROCS. AllocsPerRun(runs, f) "returns the average number of allocations during calls to f", after one warm-up call.
1 go test -run '^$' -bench 'Join' -benchmem ./bench
2 -run '^$' no tests, only benchmarks
3 BenchmarkJoin/plus/n=1000-12 1802 735422 ns/op 8539655 B/op 1998 allocs/op
4 BenchmarkJoin/builder/n=1000-12 256314 4834 ns/op 8192 B/op 1 allocs/op
5 columns: name-GOMAXPROCS, iterations, time, bytes, allocations (and custom units such as bytes/op)Real scenario: a pull request that adds an allocation in a JSON hot path, caught by TestJoinBuilderAllocs in normal CI instead of a benchmark nobody runs; a lock-free counter compared with a mutex under RunParallel -cpu 1,4,8; an encoder that reports MB/s with SetBytes.
| Knob | Where | Effect |
|---|---|---|
-benchmem | Command line | B/op and allocs/op for all benchmarks |
b.ReportAllocs() | One benchmark | Same, always on for it |
b.ResetTimer() | After setup, b.N style | Zero time and alloc counters |
b.StopTimer() / b.StartTimer() | Around per-iteration setup | Pause timing (costly; avoid in hot loops) |
b.ReportMetric(v, "unit/op") | After the loop | Extra column; ns/op set to 0 hides it |
b.SetBytes(n) | Before the loop | Adds MB/s |
b.Elapsed() | Anywhere (1.20) | Measured time so far, for rates |
-benchtime 2s, -benchtime 1000x | Command line | Longer runs or exact iteration count |
-cpu 1,2,4 | Command line | Repeat per GOMAXPROCS |
testing.AllocsPerRun(n, f) | Ordinary test | Fail when allocations regress |
Fix / how to use it: the code being measured:
// Package bench builds a comma-separated list in two ways so that the
// benchmarks next to it have something real to compare.
package bench
import "strings"
// JoinPlus concatenates with +=, allocating a new string on every step.
func JoinPlus(items []string) string {
s := ""
for i, it := range items {
if i > 0 {
s += ","
}
s += it
}
return s
}
// JoinBuilder sizes a strings.Builder once and writes into it.
func JoinBuilder(items []string) string {
n := 0
for _, it := range items {
n += len(it) + 1
}
var b strings.Builder
b.Grow(n)
for i, it := range items {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(it)
}
return b.String()
}
// Items returns n short strings, used as benchmark input.
func Items(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = "sku-" + strings.Repeat("x", i%7)
}
return out
}benchstat and continuous benchmarking Important
In plain words: Run the benchmarks ten times before your change and ten times after, save each output to a file, and run benchstat old.txt new.txt. It prints the median, the spread and whether the difference is statistically significant; ~ means "no significant change".
Common misunderstanding: "A 3 % faster number means my change helped." Laptops throttle, other processes interrupt, and one run is one sample. benchstat's doc: "Each benchmark should be run at least 10 times to gather a statistically significant sample of results. For each benchmark, benchstat computes the median and the confidence interval for the median." Second one: comparing runs from different machines. Only compare runs from the same hardware, same Go version, same load.
Definition: golang.org/x/perf/cmd/benchstat reads the standard Go benchmark format (design document 14313) and, with two or more inputs, compares each benchmark "in the first file to the same benchmark in each subsequent file and reports whether there was a statistically significant difference". The testing package doc points to it: benchstat "performs statistically robust A/B comparisons". Install with go install golang.org/x/perf/cmd/benchstat@latest. Continuous benchmarking means running the same benchmarks on every merge (or nightly) on a dedicated, quiet machine and storing the results so a regression shows as a step in a time series.
1 git switch main; go test -run '^$' -bench . -count=10 ./bench > old.txt
2 git switch feature; go test -run '^$' -bench . -count=10 ./bench > new.txt
3 benchstat old.txt new.txt
4 │ old.txt │ new.txt │
5 │ sec/op │ sec/op vs base │
6 Encode/format=json-48 1.718µ ± 1% 1.423µ ± 1% -17.20% (p=0.000 n=10)
7 Encode/format=gob-48 3.066µ ± 0% 3.070µ ± 2% ~ (p=0.446 n=10)
(lines 4-7: the example output from benchstat's own documentation)Real scenario: a pull-request bot that runs a small benchmark set on main and on the branch on the same runner and posts the benchstat table; a nightly job that stores medians in a database and alerts on a 10 % regression; a performance review where every claim of "faster" comes with p and n.
| Practice | Why |
|---|---|
-count=10 or more per side | benchstat needs samples |
-run '^$' | Do not mix test time and noise into benchmark runs |
| Same machine, same Go, idle | Hardware and toolchain dominate small differences |
| Interleave or alternate runs | Thermal drift affects old and new equally |
| Keep raw outputs as CI artifacts | Re-analyse later, compare more than two |
| Alert on significant change only | ~ is not a regression |
| Benchmarks small and focused | One hot path per benchmark |
Fix / how to use it: store results in a table and query regressions per benchmark. A minimal schema for a continuous-benchmarking job (PostgreSQL syntax):
CREATE TABLE bench_result (
id bigserial PRIMARY KEY,
commit_sha text NOT NULL,
go_version text NOT NULL,
runner text NOT NULL, -- the dedicated machine
benchmark text NOT NULL, -- e.g. 'Join/builder/n=100-12'
ns_per_op double precision NOT NULL, -- median over -count=10
allocs_op integer,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Benchmarks whose latest median is more than 10% slower than the previous one on the same runner.
SELECT benchmark, prev_ns, ns_per_op,
round((100.0 * (ns_per_op - prev_ns) / prev_ns)::numeric, 1) AS pct_change -- round(x, n) needs numeric
FROM (
SELECT benchmark, ns_per_op, runner, created_at,
lag(ns_per_op) OVER (PARTITION BY runner, benchmark ORDER BY created_at) AS prev_ns,
row_number() OVER (PARTITION BY runner, benchmark ORDER BY created_at DESC) AS rn
FROM bench_result
) t
WHERE rn = 1 AND prev_ns IS NOT NULL AND ns_per_op > prev_ns * 1.10;Profiles from tests: pprof -cpuprofile -memprofile Important
In plain words: A benchmark tells you how slow; a profile tells you where. Add -cpuprofile cpu.out -memprofile mem.out to a go test -bench run and open the files with go tool pprof.
Common misunderstanding: "The profile only covers my function." It covers the whole test binary for the run, including the testing framework and the runtime; a CPU profile of a tiny benchmark is dominated by scheduler and syscalls (the lab shows runtime.kevent on top). Use the memory profile with -sample_index=alloc_space to find who allocates, and -run '^$' so tests do not pollute it.
Definition: -cpuprofile cpu.out "Write a CPU profile to the specified file before exiting"; -memprofile mem.out "Write an allocation profile to the file after all tests have passed"; both write the test binary as -c would (keep it with -o), and go help testflag notes that "The -sample_index=alloc_space, -sample_index=alloc_objects, and -show_bytes options of pprof control how the information is presented". Others: -blockprofile, -mutexprofile, -trace, -memprofilerate. Files go to -outputdir (default: the current directory).
1 go test -run '^$' -bench 'Join/plus/n=1000$' -cpuprofile cpu.out -memprofile mem.out -o bench.test ./bench
2 go tool pprof -top bench.test cpu.out where time goes
3 go tool pprof -top -sample_index=alloc_space bench.test mem.out
4 22.75GB 84.12% academy/testing-benchmarking/bench.JoinPlus (inline)
5 go tool pprof -http=:8080 bench.test mem.out flame graph in a browserReal scenario: a benchmark that got slower after a refactor, profiled to find a new fmt.Sprintf in the loop; a memory profile showing that a decoder copies the whole body; a mutex profile under RunParallel showing contention on one lock. The broader diagnostics landscape (runtime/pprof in production, net/http/pprof, tracing) is covered on go.dev/doc/diagnostics.
| Flag | Profile | Read with |
|---|---|---|
-cpuprofile f | CPU samples | go tool pprof -top / -http |
-memprofile f | Allocations (alloc_space, inuse_space) | -sample_index=alloc_space |
-blockprofile f | Goroutine blocking | go tool pprof |
-mutexprofile f | Mutex contention | go tool pprof |
-trace f | Execution trace | go tool trace |
Fix / how to use it: profile one benchmark at a time, keep the binary with -o, write outputs into a scratch directory, and confirm the fix with benchstat rather than with the profile.
Coverage: -cover, -coverprofile, -covermode=atomic, go tool cover Must-know
In plain words: go test -cover prints the percentage of statements your tests executed. -coverprofile=c.out saves the details, and go tool cover -html=c.out shows the code in green and red; -func lists the percentage per function.
Common misunderstanding: "100 % coverage means the code is tested." Coverage says a statement ran, not that a test checked its result; a test with no assertions can reach 100 %. Second: "coverage is per module". By default it is per package ("The default is for each test to analyze only the package being tested"); code exercised from another package's tests counts only with -coverpkg.
Definition: coverage "works by annotating the source code before compilation" (Rob Pike: the tool rewrites the source with counters). -covermode set,count,atomic: "The default is 'set' unless -race is enabled, in which case it is 'atomic'"; set is "does this statement run?", count is "how many times", atomic is "count, but correct in multithreaded tests; significantly more expensive". -cover, -covermode, -coverpkg and -coverprofile each imply coverage. Since Go 1.22, packages without test files report coverage: 0.0% of statements instead of [no test files].
1 go test -cover ./after ./httpapi ./fuzz
2 ok .../after coverage: 100.0% of statements
3 ok .../httpapi coverage: 89.1% of statements
4 go test -covermode=atomic -coverprofile=c.out ./httpapi
5 go tool cover -func=c.out -> NewHandler 84.6% ... total: (statements) 89.1%
6 go tool cover -html=c.out -> red lines: the 500 branches no test reachedReal scenario: a pull request gate on "no drop in coverage of changed files"; finding the error branches no test reaches (here: the store returning an unexpected error); -coverpkg=./... for a service whose handler tests also exercise the repository package; a heat map with -covermode=count to see hot paths.
| Mode | Counter | Cost | Use |
|---|---|---|---|
set (default) | Bool per block | Lowest | Everyday percentage |
count | Int per block | Low | Heat maps |
atomic (default with -race) | Atomic int | Highest | Parallel tests, exact counts |
| Command | Output |
|---|---|
go test -cover ./... | Percentage per package |
go test -coverprofile=c.out ./... | Profile file (text format, one line per block) |
go tool cover -func=c.out | Percentage per function and total |
go tool cover -html=c.out | Annotated source in a browser |
go test -coverpkg=./... ./... | Count coverage across package boundaries |
Fix / how to use it: treat coverage as a search tool for untested branches, not a target; read the red lines in the HTML report and ask whether each one hides a behaviour worth a test.
Coverage of integration tests (GOCOVERDIR) Important
In plain words: Since Go 1.20 you can build a real program with coverage, go build -cover, run it as many times as your integration tests need with GOCOVERDIR=dir, and then ask go tool covdata how much of the code those runs covered.
Common misunderstanding: "Integration tests can not be measured because they are not go test." That was true until Go 1.20; Than McIntosh's post explains that "Because the integration test binaries are built with 'go build' and not 'go test', Go's tooling didn't provide any easy way to collect a coverage profile for these tests, up until now." And "the binary writes coverage automatically": without GOCOVERDIR it prints warning: GOCOVERDIR not set, no coverage data emitted.
Definition: "Binaries built with '-cover' write out profile data files at the end of their execution to a directory specified via the environment variable GOCOVERDIR." Each run adds files; go tool covdata percent -i=dir reports per package ("correspond directly to those reported by go test -cover"), covdata textfmt -i=dir -o profile.txt converts to the legacy format for go tool cover -func/-html, covdata merge combines directories. -coverpkg selects packages. A server that never exits can flush data with the runtime/coverage package (Go 1.20).
1 go build -cover -o greet ./covermain && mkdir covdata GOCOVERDIR must be an existing directory
2 GOCOVERDIR=covdata ./greet -name ada hello, ada
3 GOCOVERDIR=covdata ./greet -name ada -shout HELLO, ADA
4 GOCOVERDIR=covdata ./greet error: missing -name (exit 2)
5 go tool covdata percent -i=covdata covermain coverage: 100.0% of statements
6 ./greet -name x (no GOCOVERDIR) warning: GOCOVERDIR not set, no coverage data emittedReal scenario: an end-to-end suite that drives a CLI with real flags and files; a service started in CI, hit by an API test suite, then stopped gracefully; merging unit coverage and integration coverage into one report; finding the flag combinations no integration test covers.
| Step | Unit coverage | Integration coverage |
|---|---|---|
| Build | go test -cover (implicit) | go build -cover [-coverpkg=...] |
| Run | The test binary | Your program, with GOCOVERDIR set |
| Data | -coverprofile text file | Binary files in a directory |
| Report | go tool cover | go tool covdata percent, then textfmt + go tool cover |
| Merge | n/a | go tool covdata merge -i=a,b -o merged |
Fix / how to use it: the program used in the lab is tiny on purpose; the same commands apply to a real server.
// Command covermain is a tiny CLI used in the lab to collect coverage from
// a built binary (go build -cover, GOCOVERDIR), as an integration test would.
package main
import (
"flag"
"fmt"
"os"
"strings"
)
func main() {
name := flag.String("name", "", "who to greet")
shout := flag.Bool("shout", false, "upper-case the greeting")
flag.Parse()
msg, err := greet(*name, *shout)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(2)
}
fmt.Println(msg)
}
func greet(name string, shout bool) (string, error) {
if name == "" {
return "", fmt.Errorf("missing -name")
}
msg := "hello, " + name
if shout {
msg = strings.ToUpper(msg)
}
return msg, nil
}Fuzzing: testing.F, FuzzXxx, f.Add Must-know
In plain words: A fuzz test gives the fuzzing engine a function and some example inputs. The engine mutates the inputs millions of times, guided by which code they reach, looking for one that makes your function fail or panic. You write a property ("parsing what I formatted gives back the same value"), not individual cases.
Common misunderstanding: "Fuzz tests only run with -fuzz." Without it, the fuzz test runs its seed corpus like a table-driven test, every time: "When fuzzing is disabled, the fuzz target is called with the seed inputs registered with F.Add and seed inputs from testdata/fuzz/<Name>". So every crasher you commit becomes a permanent regression test. Second one: "the fuzzer can generate my structs". Arguments are limited to string, []byte, the integer types, float32, float64 and bool.
Definition: func FuzzXxx(f *testing.F); f.Add(...) registers seeds whose types "must be identical to the types of these parameters"; f.Fuzz(func(t *testing.T, args...)) is the fuzz target, which fails "by calling T.Fail (or any method that calls it like T.Error or T.Fatal) or by panicking"; t.Skip marks an input as uninteresting. With -fuzz=FuzzXxx (exactly one target in one package) the engine runs workers (-parallel, default GOMAXPROCS) until failure, Ctrl-C or -fuzztime. A failing input is minimised (-fuzzminimizetime, default 60s) and written to testdata/fuzz/FuzzXxx/ in the go test fuzz v1 format; inputs that expand coverage are cached in $GOCACHE/fuzz, which the Go 1.18 notes warn "may occupy a large amount of storage (possibly several GBs)". Coverage guidance needs AMD64 or ARM64.
1 go test ./fuzz seeds: FuzzParseAmount/seed#0..#9, /leading-zeros -> PASS
2 go test -run '^$' -fuzz FuzzParseAmount -fuzztime 10s ./fuzz
3 fuzz: elapsed: 0s, gathering baseline coverage: 11/11 completed, now fuzzing with 12 workers
4 fuzz: elapsed: 3s, execs: 2168156 (722704/sec), new interesting: 10 (total: 21)
5 ... PASS after 7.2 million executions
6 on a bug: "Failing input written to testdata/fuzz/FuzzParseAmount/<hash>"; commit it
7 go test -run=FuzzParseAmount/<hash> ./fuzz reproduce exactly that inputReal scenario: parsers of money, dates, URLs, CSV and binary formats; round-trip properties (encode/decode, format/parse, compress/decompress); differential fuzzing (your fast implementation vs a slow reference); input validation in front of a security boundary (the fuzzing blog stresses that fuzzing is "particularly valuable for finding security exploits and vulnerabilities").
| Fuzzing fact | Value |
|---|---|
| Function | func FuzzXxx(f *testing.F) |
| Seed corpus | f.Add(...) + files in testdata/fuzz/FuzzXxx/ |
| Generated corpus | $GOCACHE/fuzz (not committed) |
| Argument types | string, []byte, int*, uint*, float32, float64, bool |
| One target per run | -fuzz must match exactly one fuzz test in one package |
| Duration | -fuzztime 30s or -fuzztime 1000x; default forever |
| Minimisation | -fuzzminimizetime, default 60s; 0 disables |
| Coverage guidance | AMD64 and ARM64 |
| Corpus file header | go test fuzz v1 |
| Since | Go 1.18 |
Fix / how to use it: the parser below rejects anything but digits with at most two decimals; the fuzz test checks the round trip for every accepted input. The committed seed file testdata/fuzz/FuzzParseAmount/leading-zeros contains go test fuzz v1 and string("007.10").
// Package fuzz parses and formats money amounts such as "12.34" as cents.
// Its fuzz test checks the round trip Format(Parse(s)) for every input the
// engine invents.
package fuzz
import (
"errors"
"strconv"
"strings"
)
// ErrSyntax is returned for input that is not a non-negative amount with at
// most two decimals.
var ErrSyntax = errors.New("invalid amount")
// ParseAmount turns "12", "12.3" or "12.34" into cents.
func ParseAmount(s string) (int64, error) {
whole, frac, hasDot := strings.Cut(s, ".")
if whole == "" || len(frac) > 2 || (hasDot && frac == "") {
return 0, ErrSyntax
}
if !digits(whole) || !digits(frac) {
return 0, ErrSyntax
}
w, err := strconv.ParseInt(whole, 10, 64)
if err != nil || w > (1<<62)/100 {
return 0, ErrSyntax
}
for len(frac) < 2 {
frac += "0"
}
f, _ := strconv.ParseInt(frac, 10, 64)
return w*100 + f, nil
}
// FormatAmount turns cents into "12.34".
func FormatAmount(cents int64) string {
return strconv.FormatInt(cents/100, 10) + "." + pad2(cents%100)
}
func pad2(n int64) string {
if n < 10 {
return "0" + strconv.FormatInt(n, 10)
}
return strconv.FormatInt(n, 10)
}
func digits(s string) bool {
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}package fuzz
import (
"errors"
"testing"
)
// With plain go test, FuzzParseAmount runs the f.Add seeds and the files in
// testdata/fuzz/FuzzParseAmount as subtests. With -fuzz=FuzzParseAmount the
// engine mutates them, guided by coverage, until a failure or -fuzztime.
func FuzzParseAmount(f *testing.F) {
for _, seed := range []string{"0", "12", "12.3", "12.34", "0.05", "", ".5", "1.234", "-1", "1e3"} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, s string) {
cents, err := ParseAmount(s)
if err != nil {
if !errors.Is(err, ErrSyntax) {
t.Fatalf("ParseAmount(%q) returned unexpected error %v", s, err)
}
t.Skip() // invalid input is not a failure
}
if cents < 0 {
t.Fatalf("ParseAmount(%q) = %d, want >= 0", s, cents)
}
// Property: formatting and parsing again gives the same cents.
back, err := ParseAmount(FormatAmount(cents))
if err != nil || back != cents {
t.Fatalf("round trip %q -> %d -> %q -> %d, %v", s, cents, FormatAmount(cents), back, err)
}
})
}The race detector in tests (-race) Must-know
In plain words: go test -race builds the tests with the race detector, which watches every memory access at run time and fails the test when two goroutines touch the same variable without synchronisation and at least one writes.
Common misunderstanding: "My tests pass with -race, so there are no races." The detector only sees races that happen in the executions it observes; code paths your tests never run concurrently are not checked. Run concurrent paths in tests (parallel subtests, -count), and keep -race on in CI. The race detector itself, and how to fix what it finds, is the subject of Race Conditions & Deadlocks.
Definition: with -race, a test that triggers a report fails with race detected during execution of test after a WARNING: DATA RACE block; the coverage mode defaults to atomic; the race build tag is set; the binary is slower and uses more memory, so CI often runs -race and a fast run separately.
1 go test -count=1 ./racedemo ok (the race happened, nobody noticed)
2 go test -race -count=1 ./racedemo WARNING: DATA RACE ...
3 --- FAIL: TestCounter
4 testing.go:1867: race detected during execution of test
5 FAILReal scenario: a handler test that shares a map-backed fake store between parallel subtests; an in-memory cache with a forgotten lock; a callback invoked from a goroutine writing to a test-local slice.
| Run | Finds | Cost |
|---|---|---|
go test ./... | Logic bugs | Fast |
go test -race ./... | Data races on executed paths | Slower, more memory |
go test -race -count=20 -run TestX | Intermittent races | Longer |
go test -race -shuffle=on | Races depending on order | Seed printed for replay |
Fix / how to use it: make -race the default in CI; when it reports, read both stacks, fix the synchronisation, and add the reproducing test permanently.
Time in tests and synctest (Go 1.25 testing/synctest) Important
In plain words: Code that depends on time.Now, time.Sleep or timers is slow and flaky to test with the real clock. Either inject a clock (a func() time.Time your test advances by hand), or, from Go 1.25, run the test inside synctest.Test, where the time package uses a fake clock that jumps forward whenever every goroutine in the test is blocked.
Common misunderstanding: "time.Sleep(100 * time.Millisecond) in a test is fine for waiting on a goroutine." It makes the suite slow and fails on a loaded CI machine. Second one: "synctest fakes everything". It fakes time and knows which goroutines are durably blocked; a goroutine blocked on a mutex, on network I/O or on a system call is "not durably blocking", so code that talks to a real network inside a bubble does not get the fake-time speedup ("Avoid using the network. Use a fake network implementation as needed.").
Definition: "The Test function runs a test function in an isolated 'bubble'. Within the bubble, time is virtualized: time package functions operate on a fake clock and the clock moves forward instantaneously if all goroutines in the bubble are blocked." The initial time is "midnight UTC 2000-01-01". synctest.Wait "blocks until every goroutine within the current bubble, other than the current goroutine, is durably blocked". Test "waits for all goroutines in the bubble to exit before returning", and the t inside has a Context whose Done channel belongs to the bubble; T.Run, T.Parallel and T.Deadline must not be called. History: Go 1.24 shipped it as an experiment (GOEXPERIMENT=synctest, synctest.Run), Go 1.25 made it generally available with synctest.Test, Go 1.27 added synctest.Sleep and httptest.NewTestServer for an in-memory network that works inside bubbles.
inside synctest.Test (fake clock starts at 2000-01-01 00:00 UTC)
1 s.Touch("alice") seen = {alice: 00:00}
2 go s.Reap(t.Context(), time.Minute) ticker every fake minute
3 time.Sleep(29 * time.Minute) all goroutines blocked -> clock jumps tick by tick to 00:29
4 synctest.Wait(); s.Len() == 1 alice still valid
5 time.Sleep(2 * time.Minute); Wait 00:31: reaper deleted alice -> s.Len() == 0
6 test ends: t.Context canceled, Reap returns, Test returns real time: microsecondsReal scenario: session expiry, token refresh before expiry, retry with backoff, rate limiters, debouncers, cache TTLs, scheduled jobs, timeouts in clients. The time package itself is covered in time.Time & Timers.
| Approach | Changes production code? | Fast | Deterministic | Works with real goroutines and timers |
|---|---|---|---|---|
Real clock + time.Sleep in the test | No | No | No (flaky) | Yes |
Injected now func() time.Time | Yes (small) | Yes | Yes | Only for Now, not for timers |
| Clock interface with fake timers (library) | Yes | Yes | Yes | If every timer goes through it |
testing/synctest bubble (Go 1.25+) | No | Yes | Yes | Yes, except network, mutex waits, syscalls |
Fix / how to use it: both approaches, on the same session store:
// Package clock is a session store whose expiry depends on time. Production
// code uses the real clock; tests inject a fake one, or (Go 1.25+) run the
// real time package inside a testing/synctest bubble.
package clock
import (
"context"
"sync"
"time"
)
// Sessions remembers when each session was last seen.
type Sessions struct {
mu sync.Mutex
ttl time.Duration
now func() time.Time // injectable clock
seen map[string]time.Time
}
// New returns a store whose sessions expire after ttl. A nil now means
// time.Now.
func New(ttl time.Duration, now func() time.Time) *Sessions {
if now == nil {
now = time.Now
}
return &Sessions{ttl: ttl, now: now, seen: map[string]time.Time{}}
}
// Touch marks id as active now.
func (s *Sessions) Touch(id string) {
s.mu.Lock()
defer s.mu.Unlock()
s.seen[id] = s.now()
}
// Valid reports whether id was touched less than ttl ago.
func (s *Sessions) Valid(id string) bool {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.seen[id]
return ok && s.now().Sub(t) < s.ttl
}
// Len is the number of remembered sessions.
func (s *Sessions) Len() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.seen)
}
// Reap deletes expired sessions every interval until ctx is canceled.
func (s *Sessions) Reap(ctx context.Context, interval time.Duration) {
tick := time.NewTicker(interval)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
s.mu.Lock()
for id, t := range s.seen {
if s.now().Sub(t) >= s.ttl {
delete(s.seen, id)
}
}
s.mu.Unlock()
}
}
}package clock
import (
"sync"
"testing"
"time"
)
// fakeClock is advanced by the test; no sleeping, no flakiness.
type fakeClock struct {
mu sync.Mutex
t time.Time
}
func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}
func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.t = c.t.Add(d)
}
func TestValidWithFakeClock(t *testing.T) {
t.Parallel()
clk := &fakeClock{t: time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)}
s := New(30*time.Minute, clk.Now)
s.Touch("alice")
clk.Advance(29 * time.Minute)
if !s.Valid("alice") {
t.Error("session invalid after 29m, want valid (ttl 30m)")
}
clk.Advance(time.Minute)
if s.Valid("alice") {
t.Error("session valid after 30m, want expired")
}
}//go:build go1.25
// testing/synctest is generally available from Go 1.25. The build tag keeps
// this file out of older toolchains and raises this file's language version,
// while the module itself still says go 1.24.
package clock
import (
"testing"
"testing/synctest"
"time"
)
// Inside the bubble time.Now, time.Sleep and tickers use a fake clock that
// jumps forward whenever every goroutine in the bubble is durably blocked.
// The test "waits" 31 minutes and finishes in microseconds.
func TestReapInBubble(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s := New(30*time.Minute, nil) // the real time.Now, faked by the bubble
s.Touch("alice")
go s.Reap(t.Context(), time.Minute) // canceled when the bubble's test ends
time.Sleep(29 * time.Minute)
synctest.Wait() // let the reaper finish its current tick
if s.Len() != 1 {
t.Fatalf("after 29m: %d sessions, want 1", s.Len())
}
time.Sleep(2 * time.Minute)
synctest.Wait()
if s.Len() != 0 {
t.Fatalf("after 31m: %d sessions, want 0 (reaped)", s.Len())
}
})
}Flaky tests Must-know
In plain words: A flaky test passes and fails on the same code. It is almost always one of five causes: real time, test order, shared state between parallel tests, the network, or unordered output (maps, goroutines) compared as if it were ordered.
Common misunderstanding: "Retry flaky tests until they pass." That hides a real bug in either the test or the code (a race, an ordering assumption) and trains everyone to ignore red builds. Quarantine the test with a tracking issue if you must, but fix the cause.
Definition: a test is deterministic when its outcome depends only on the code and its inputs. The tools that expose non-determinism are built in: -count=N repeats, -shuffle=on randomises order ("the seed will be reported for reproducibility", reuse it with -shuffle=SEED), -race finds unsynchronised sharing, -cpu 1,4 changes scheduling, -failfast stops at the first failure while you iterate, and -json lets CI record which test failed on which run.
1 go test -run TestX -count=200 ./pkg fails 3 times out of 200 -> it is flaky
2 go test -run TestX -count=200 -race ./pkg WARNING: DATA RACE -> shared state
3 go test -shuffle=on ./pkg -test.shuffle 1795864862161272000 printed
4 go test -shuffle=1795864862161272000 ./pkg same order -> reproducible failure
5 fix: own fixture per test / injected clock / sorted output / fake serverReal scenario: a test that asserts "took less than 50 ms" and fails on a busy CI runner; two tests that both write testdata/out.txt; a test that depends on a previous test having created a user; a JSON comparison of a map's encoding order; a test calling a real third-party sandbox API.
| Cause | Symptom | Fix |
|---|---|---|
| Real time, sleeps, "took less than X ms" asserts | Fails under load: scheduling delays break upper bounds | Inject a clock, synctest; assert behaviour (deadline error returned, cancellation observed), not elapsed time |
| Order dependence | Fails with -shuffle or -run alone | Each test builds its own state |
| Shared state in parallel tests | Fails with -race or -count | Per-test fixtures, no globals |
| Network, real third-party APIs | Fails offline or on their outage | httptest fakes; real calls only in integration |
| Unordered output compared as ordered | Fails one run in N | Sort, Unordered output, cmpopts.SortSlices |
| Leaked goroutines from a previous test | Odd failures in the next test | t.Context() + cleanup that waits, goleak |
| Port collisions, fixed ports | address already in use | httptest.NewServer picks a free port; NewTestServer uses none |
Fix / how to use it: every test on this page uses one of those fixes: the client timeout test asserts behaviour (it got context.DeadlineExceeded and the fake server saw the cancellation) instead of elapsed time, the handler test does not parallelise its stateful rows, the session test injects a clock, and the reaper test runs inside a synctest bubble.
Mechanics
What go test does, step by step Important
- Resolves the packages (
./...skips directories namedtestdata). - For each package, compiles the package plus its
_test.gofiles, and the_testpackage if there is one, into a test binary; a generatedmaincalls yourTestMainor the default runner. - Runs the vet subset on the package and its tests; problems are treated like build errors and the binary is not run.
- Checks the test cache: in package list mode, an identical binary with only cacheable flags, unchanged files it opened and unchanged environment variables it read, prints the old result with
(cached). - Runs the binary in the package directory with
-test.*flags, packages in parallel up to-p. - Inside the binary (
M.Run): tests (sequential ones in source order or shuffled, parallel ones resumed after the sequential ones), then fuzz seed corpora, then examples, then benchmarks (only with-bench), and finally fuzzing (only with-fuzz, "after tests, benchmarks, seed corpora of other fuzz tests, and examples have completed"). - Prints
ok,FAILor?per package; exit status 1 if any failed.
go vet in go test Must-know
go help test: "As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems. If go vet finds any problems, go test reports those and does not run the test binary. Only a high-confidence subset of the default go vet checks are used. That subset is: atomic, bools, buildtag, directive, errorsas, ifaceassert, nilfunc, printf, stdversion, stringintconv, and tests." -vet=off disables it, -vet=all runs everything. The subset grew over time: Go 1.24 added the tests analyzer ("malformed names, incorrect signatures, or examples that document non-existent identifiers"), Go 1.27 added stdversion. Checks outside the subset, such as testinggoroutine (t.Fatal from a non-test goroutine) and lostcancel, only run with an explicit go vet ./..., which CI should run as well.
| Analyzer in the subset | Catches in tests |
|---|---|
printf | t.Errorf("%d", "x"), wrong verb or argument count |
tests | func Testfoo(t *testing.T), wrong signatures, examples for missing identifiers |
errorsas | errors.As(err, val) with a non-pointer |
atomic | x = atomic.AddInt64(&x, 1) |
stdversion | Standard-library symbols newer than the file's Go version (1.27) |
bools, nilfunc, ifaceassert, stringintconv, buildtag, directive | Impossible conditions, bad build tags and directives |
Name matching for -run, -bench, -skip Important
The argument is an unanchored regular expression, "split by unbracketed slash (/) characters into a sequence of regular expressions, and each part of a test's identifier must match the corresponding element in the sequence". -run Foo matches TestFooBar; -run '^TestFoo$' matches only TestFoo; -run Foo/A= runs subtests matching A= of tests matching Foo; -run /A=1 runs that subtest in every test; -run '^$' runs nothing (used with -bench). "Possible parents of matches are run too", so setup code in the parent always runs. -run=FuzzFoo/9ddb952d9814 replays one corpus entry.
Test caching Important
Only in package list mode, and only for passing packages. Cacheable flags: "-benchtime, -coverprofile, -cpu, -failfast, -fullpath, -list, -outputdir, -parallel, -run, -short, -skip, -timeout and -v". Any other flag disables caching; "The idiomatic way to disable test caching explicitly is to use -count=1." Tests that open files in the module or read environment variables are re-run when those change. A cached result "is treated as executing in no time at all", so it is reused regardless of -timeout. go clean -testcache empties the cache.
Output formats: -v, -json, exit codes Important
| Line | Meaning |
|---|---|
=== RUN TestX | A test or subtest started (with -v) |
=== PAUSE TestX / === CONT TestX | t.Parallel paused, then resumed |
--- PASS: TestX (0.00s) / --- FAIL / --- SKIP | Result with duration |
file_test.go:42: message | t.Log/t.Error output, with file and line (-fullpath for full paths) |
ok pkg 0.39s / ok pkg (cached) | Package passed |
FAIL pkg 0.40s | Package failed |
? pkg [no test files] | No tests (packages with code report coverage: 0.0% under -cover since 1.22) |
testing: warning: no tests to run | The -run pattern matched nothing |
panic: test timed out after 10m0s | -timeout exceeded; stacks of all goroutines follow |
-test.shuffle 1795864862161272000 | Seed printed by -shuffle=on |
=== ATTR TestF key value | t.Attr (1.25) |
=== ARTIFACTS TestX /path | t.ArtifactDir with -artifacts (1.26) |
-json "presents the same information as the -v flag in a machine-readable format" as "a newline-separated sequence of TestEvent objects" (the cmd/test2json doc) with fields Time, Action, Package, Test, Elapsed, Output, OutputType, FailedBuild; Action is one of start, run, pause, cont, pass, bench, fail, output, skip, and "Every JSON stream begins with a 'start' event". Go 1.24 also reports build output and failures as JSON, Go 1.27 adds the optional OutputType. CI tools read this stream; gotestsum, for example, "runs tests using go test -json, prints formatted test output, and a summary" and can write a JUnit XML file with --junitfile. -failfast "Do not start new tests after the first test failure"; -list regexp prints top-level names without running them.
Exact texts you will meet Must-know
| Text | Source |
|---|---|
race detected during execution of test | Test failed because the race detector reported |
call to (*testing.T).Fatal from a non-test goroutine | go vet testinggoroutine |
warning: GOCOVERDIR not set, no coverage data emitted | go build -cover binary run without GOCOVERDIR |
Failing input written to testdata/fuzz/FuzzFoo/... | Fuzzer found a failure |
fuzz: elapsed: 3s, execs: ... new interesting: ... | Fuzzing progress |
testing: test using t.Setenv, t.Chdir, or cryptotest.SetGlobalRandom can not use t.Parallel (panic) | Process-wide change in a parallel test |
--- FAIL: ExampleX / got: / want: | Example output mismatch |
Solving the classic problems
| Problem | Symptom | Fix | Cost |
|---|---|---|---|
| Copy-paste tests | 40 functions, unclear coverage of edge cases | One table + t.Run | Rewrite once |
| Vague messages | "wrong value" | "F(in) = got, want want" | Discipline |
| Fatal everywhere | One failure per run | t.Error for independent checks | None |
| Errors compared by text | Test breaks when wording changes | errors.Is/errors.As | Sentinel or typed errors |
| Slow suite | Minutes per run | t.Parallel, -short, unit tests over real servers | Isolation work |
| Shared mutable fixtures | Flaky under -race/-shuffle | Fixture per test via helper + t.Cleanup | Slightly more setup time |
| Real clock | Slow, flaky | Inject clock or synctest | Small API change or Go 1.25 |
| Tests call real APIs | Fails offline | httptest.NewServer fake | Write the fake |
| Struct comparison by fields | 15 lines, partial checks | cmp.Diff(want, got, opts...) | Dependency |
| Benchmark lies | Sub-nanosecond results, setup measured | b.Loop; -count=10 + benchstat | Run time |
| Coverage only of unit tests | Integration paths invisible | go build -cover + GOCOVERDIR | CI wiring |
| Parsers never see weird input | Panics in production | Fuzz test + commit crashers | CPU time while fuzzing |
Turning copy-paste tests into a table
The Before and After packages are the template: list the cases as data, name each one, run the same checks, add the boundary values the table makes obvious.
Making a fixture safe for parallel tests
Replace package-level fixtures with a constructor newFixture(tb testing.TB) *F that calls tb.Helper(), builds a fresh instance (temporary directory, empty in-memory store, its own httptest server), and registers tb.Cleanup. If building it is expensive, build the immutable part once in TestMain and give each test its own mutable part.
Testing code that sleeps or ticks
Inject now func() time.Time for code that only reads the clock; for code that uses timers, tickers and time.Sleep, wrap the test in synctest.Test (Go 1.25+) and replace waits in the test with synctest.Wait. Do not assert on real elapsed time at all: an upper bound ("finished within 50 ms") breaks when the machine is loaded, and a lower bound only proves the code slept; assert the observable outcome instead.
Proving a change is faster
Benchmark with b.Loop, run -count=10 on both sides on the same idle machine, compare with benchstat, profile only if you need to know why, and add a testing.AllocsPerRun test if the win is "zero allocations".
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Many inputs, one rule | Table-driven tests + t.Run | Map table to randomise order | One loop, named cases |
| Different checking logic | Separate test functions | Shared helpers with testing.TB | Readable tests |
| HTTP handler | httptest.NewRequest + NewRecorder | Route table | No network, microseconds |
| HTTP client | httptest.NewServer (Go 1.27: NewTestServer) | Fake returns errors and delays | Real HTTP stack |
| Struct results | cmp.Diff | cmpopts.IgnoreFields, EquateEmpty | Readable diff |
| Team prefers assertions | testify require for setup, assert for checks | No suite with parallel tests | Familiar, still Error/Fatal semantics |
| Large exact output | Golden file in testdata | -update flag + review | Reviewed snapshot |
| Documentation | ExampleXxx with // Output: | Unordered output for maps | Docs that cannot rot |
| Package-wide expensive setup | TestMain + m.Run | Explicit teardown before os.Exit | Once per binary |
| Needs DB, network, credentials | //go:build integration | Env var + t.Skip | Default run stays hermetic |
| Slow but hermetic | testing.Short() + t.Skip | -short in pre-commit | Fast feedback |
| Time-dependent code | Injected clock; synctest (1.25+) | synctest.Wait; assert outcomes, not durations | Deterministic, fast |
| Parsers and decoders | Fuzz test with f.Add seeds | Commit crashers | Finds inputs you did not imagine |
| Performance claim | b.Loop benchmark | -count=10 + benchstat, -benchmem | Statistics, not one run |
| Allocation budget | testing.AllocsPerRun | Skip under -race, not parallel | Fails in normal CI |
| Concurrency | -race in CI | -count, -shuffle=on | Executed paths only |
| Coverage of a CLI or service | go build -cover + GOCOVERDIR | covdata textfmt + go tool cover | Integration paths counted |
In architecture: from a single process to a distributed system
Monolith: one process, one database
In one binary, most tests should be unit and handler tests that never leave the process: table-driven tests of domain logic, httptest.NewRecorder for every route, in-memory fakes behind small interfaces (Mocking with Interfaces & DI). The database layer gets integration tests behind a build tag against a real PostgreSQL started once in TestMain, with one transaction per test that is rolled back in t.Cleanup, so tests can run in parallel without seeing each other's rows:
-- Created once by TestMain (or by migrations) in the test database.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
sku text NOT NULL,
units integer NOT NULL CHECK (units > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
-- Per test: BEGIN in the helper, seed, run the code under test inside the same tx, ROLLBACK in Cleanup.
BEGIN;
INSERT INTO orders (sku, units) VALUES ('MUG-01', 2), ('PEN-22', 12);
SELECT count(*) FROM orders WHERE units > 5; -- the assertion the Go test makes: 1
ROLLBACK; -- nothing leaks into the next testExample: a Laravel-shaped Go monolith with 600 unit tests (2 s with t.Parallel), 40 handler tests, 25 repository tests with -tags integration (20 s), all with -race in CI. Transactions themselves are explained in ACID & Transactions, the repository layer in database/sql & pgx.
Modular monolith and multiple databases
Module boundaries become test boundaries: each module has its own fakes for the other modules' public interfaces, and a few cross-module tests exercise the real wiring. Black-box tests (package billing_test) prove that a module's exported API is enough. With two stores (PostgreSQL for orders, Redis for sessions), each gets its own integration tests and its own build tag or skip condition; coverage across modules needs -coverpkg=./... because handler tests in one package exercise code in others. The rule from Low-Level Design applies: if a module is hard to test without the others, the boundary is in the wrong place.
Microservices
Across services the expensive tests multiply, so push checks down: each service tests its own handlers with httptest, tests its clients against httptest.NewServer fakes that return the other service's real error shapes, and verifies the contract (consumer-driven contract tests, or schema checks for protobuf and OpenAPI) rather than starting every dependency. A multi-service example: checkout calls payments over HTTP and publishes OrderPlaced; checkout's tests fake payments with NewServer returning 200, 402, 502 and a 3 s delay (the timeout test asserts context.DeadlineExceeded and that no event was published); payments verifies the same request shape in its own handler tests; the event consumer is tested with an in-memory broker (Testing Messaging Systems). Only a handful of end-to-end tests run against a deployed environment, and their coverage is collected with go build -cover and GOCOVERDIR in each service image. What does not survive the boundary: t.Parallel isolation (a shared staging database is shared), t.Cleanup (cleanup across services needs idempotent test data or per-run tenants, see API Idempotency), and deterministic time.
Distributed data: replicas, caches, sharded databases, multi-region
Behaviour that only appears with replication lag, cache staleness or partitions cannot be proven by unit tests of the happy path. Make the distributed effects injectable and test them deterministically: a fake replica that returns stale rows to test read-your-writes fallbacks; a cache fake with a controllable TTL driven by a fake clock or synctest; a shard router tested table-driven over key ranges; fuzz tests for the shard-key hash (no panic, stable distribution). Real-cluster tests (failover, partition) are integration or chaos tests outside go test's default run, tagged and scheduled. Benchmarks of a client library against a remote cluster measure the network, not your code; benchmark the serialisation and routing locally and measure the cluster with load tests.
Scaling path: 1×, 10×, 100×
| Scale | What changes | Testing practice |
|---|---|---|
| 1× (one team, one service) | Suite under a minute | Table-driven tests, httptest, -race in CI, go vet ./... |
| 10× (several teams, a monorepo or a few services) | Suite takes minutes, flakes appear | t.Parallel everywhere safe, -short locally, integration behind tags, -shuffle=on and -json reports in CI, flaky-test quarantine with an issue |
| 100× (many services, performance-sensitive paths) | Regressions slip in, CI cost matters | Continuous benchmarking on dedicated runners with benchstat, fuzzing nightly with committed corpora, integration coverage via GOCOVERDIR, test selection by changed packages (the cache does part of this) |
Lab
All commands run from docs/snippets/go/testing-benchmarking/go; commands that write files (profiles, coverage, fuzz corpora) were run in a scratch copy so nothing lands in the snippet tree. Outputs marked (real) were produced on Go 1.27.4, macOS, Apple M4 Pro.
1. Run everything with the race detector (real)
go vet ./... && go test -race -count=1 ./...
# ok academy/testing-benchmarking/after 1.394s
# ok academy/testing-benchmarking/before 1.390s
# ok academy/testing-benchmarking/bench 1.394s
# ok academy/testing-benchmarking/clock 1.393s
# ok academy/testing-benchmarking/compare 1.431s
# ok academy/testing-benchmarking/covermain 1.396s
# ok academy/testing-benchmarking/fuzz 1.399s
# ok academy/testing-benchmarking/golden 1.399s
# ok academy/testing-benchmarking/helpers 1.399s
# ok academy/testing-benchmarking/httpapi 1.455s
# ok academy/testing-benchmarking/testmain 1.521s2. Select subtests, examples and short mode (real)
go test -count=1 -v -run 'TestDiscount/ten_off' ./after
# === RUN TestDiscount
# === PAUSE TestDiscount
# === CONT TestDiscount
# === RUN TestDiscount/ten_off_at_threshold
# === PAUSE TestDiscount/ten_off_at_threshold
# === RUN TestDiscount/ten_off_below_threshold
# === PAUSE TestDiscount/ten_off_below_threshold
# --- PASS: TestDiscount (0.00s)
# --- PASS: TestDiscount/ten_off_at_threshold (0.00s)
# --- PASS: TestDiscount/ten_off_below_threshold (0.00s)
go test -count=1 -v -run Example ./after
# --- PASS: ExampleDiscount (0.00s)
# --- PASS: Example_unordered (0.00s)
go test -count=1 -short -v -run TestEvery ./testmain
# main_test.go:62: walks the full catalog; skipped with -short
# --- SKIP: TestEveryProductHasAName (0.00s)
go test -count=1 -shuffle=on ./before -v | grep shuffle
# -test.shuffle 17958648621612720003. Benchmarks with allocations (real)
go test -run '^$' -bench . -benchmem ./bench
# cpu: Apple M4 Pro
# BenchmarkJoin/plus/n=10-12 4424119 275.3 ns/op 832 B/op 18 allocs/op
# BenchmarkJoin/builder/n=10-12 25166575 47.68 ns/op 80 B/op 1 allocs/op
# BenchmarkJoin/plus/n=100-12 137436 8974 ns/op 83536 B/op 198 allocs/op
# BenchmarkJoin/builder/n=100-12 2623640 456.9 ns/op 896 B/op 1 allocs/op
# BenchmarkJoin/plus/n=1000-12 1802 735422 ns/op 8539655 B/op 1998 allocs/op
# BenchmarkJoin/builder/n=1000-12 256314 4834 ns/op 8192 B/op 1 allocs/op
# BenchmarkJoinBuilderN-12 264646 4634 ns/op 8192 B/op 1 allocs/op
# BenchmarkJoinBuilderParallel-12 4922794 244.4 ns/op 896 B/op 1 allocs/op
# BenchmarkJoinBytes-12 2594809 460.8 ns/op 794.0 bytes/op 896 B/op 1 allocs/opThe b.N-style BenchmarkJoinBuilderN (4634 ns/op) and the b.Loop sub-benchmark builder/n=1000 (4834 ns/op) measure the same call; RunParallel reports wall time for all 12 goroutines together.
4. Compare with benchstat (expected, not run)
go install golang.org/x/perf/cmd/benchstat@latest
go test -run '^$' -bench 'Join/builder' -count=10 ./bench > new.txt # after the change
# (old.txt: same command on the previous commit)
benchstat old.txt new.txt
# expected shape: one row per benchmark, "± x%" spread, and either "-NN.NN% (p=0.000 n=10)"
# or "~ (p=0.4xx n=10)" when the difference is not significant5. Profile a benchmark (real)
go test -run '^$' -bench 'Join/plus/n=1000$' -benchtime 2s -cpuprofile cpu.out -memprofile mem.out -o bench.test ./bench
go tool pprof -top -sample_index=alloc_space -nodecount 4 bench.test mem.out
# 22.75GB 84.12% 84.12% 22.75GB 84.12% academy/testing-benchmarking/bench.JoinPlus (inline)
# 4.29GB 15.86% 100% 4.29GB 15.86% internal/bytealg.MakeNoZero
go tool pprof -top -nodecount 3 bench.test cpu.out
# 2340ms 35.19% runtime.kevent (the runtime dominates a tiny benchmark)6. Coverage, unit and integration (real)
go test -count=1 -cover ./after ./httpapi ./fuzz
# ok .../after coverage: 100.0% of statements
# ok .../httpapi coverage: 89.1% of statements
# ok .../fuzz coverage: 95.0% of statements
go test -covermode=atomic -coverprofile=cover.out ./httpapi && go tool cover -func=cover.out | tail -2
# .../httpapi/handler.go:97: writeJSON 100.0%
# total: (statements) 89.1%
go build -cover -o greet ./covermain
mkdir covdata # the directory must exist before the runs
GOCOVERDIR=covdata ./greet -name ada # hello, ada
GOCOVERDIR=covdata ./greet -name ada -shout # HELLO, ADA
GOCOVERDIR=covdata ./greet # error: missing -name (exit 2)
go tool covdata percent -i=covdata
# academy/testing-benchmarking/covermain coverage: 100.0% of statements
./greet -name x
# warning: GOCOVERDIR not set, no coverage data emitted7. Fuzz for ten seconds (real)
go test -run '^$' -fuzz FuzzParseAmount -fuzztime 10s ./fuzz
# fuzz: elapsed: 0s, gathering baseline coverage: 11/11 completed, now fuzzing with 12 workers
# fuzz: elapsed: 3s, execs: 2168156 (722704/sec), new interesting: 10 (total: 21)
# fuzz: elapsed: 10s, execs: 7265025 (653264/sec), new interesting: 10 (total: 21)
# PASS8. Watch -race and vet catch what go test alone does not (real)
The module is saved in the repository at pipeline/sources/testing-benchmarking/lab8/ (go.mod and r_test.go: TestCounter, where two goroutines increment an int without a lock, and TestFatalInGoroutine, which calls t.Fatal inside a goroutine; line 29 is that call). It lives outside the snippet module on purpose, because the snippet module must pass -race and go vet. Run these from that directory:
go test -count=1 . # ok racedemo (both bugs invisible)
go test -race -count=1 -run TestCounter .
# WARNING: DATA RACE
# --- FAIL: TestCounter (0.00s)
# testing.go:1867: race detected during execution of test
go vet .
# r_test.go:29:4: call to (*testing.T).Fatal from a non-test goroutineFor PHP/Laravel developers
PHPUnit and Pest are frameworks: test classes extend TestCase, setUp/tearDown run around each test (Laravel's docs remind you to call parent::setUp()), and data providers attached with the PHPUnit\Framework\Attributes\DataProvider attribute feed cases. Laravel adds HTTP tests that call routes in-process, plus the RefreshDatabase trait, which, when the schema is up to date, will "only execute the test within a database transaction" (Laravel 13 database-testing docs). Go has the same ideas without a framework: a test is a function, a data provider is a table, setUp/tearDown are a helper plus t.Cleanup, an in-process HTTP test is httptest.NewRecorder, and RefreshDatabase is the "transaction per test, rollback in cleanup" helper shown in the monolith section. The biggest habit change: in Go you choose per check whether a failure stops the test (t.Fatal, testify require) or lets it continue (t.Error, testify assert), and the Go convention is to continue.
// Laravel feature test: the same check as the Go handler table, one case.
public function test_missing_order_returns_404(): void
{
$this->getJson('/orders/99')
->assertStatus(404)
->assertJson(['message' => 'order not found']);
}| PHPUnit / Pest / Laravel | Go |
|---|---|
class OrderTest extends TestCase | func TestOrder(t *testing.T) in order_test.go |
#[DataProvider('additionProvider')] | Table-driven tests with t.Run |
setUp(), tearDown() | Helper + t.Cleanup; TestMain for once-per-package |
$this->assertSame() | if got != want { t.Errorf(...) }, or testify assert/require |
$this->getJson('/x')->assertStatus(200)->assertJson([...]) | httptest.NewRequest + NewRecorder + ServeHTTP |
Http::fake([...]) | httptest.NewServer(fakeHandler) |
RefreshDatabase | Transaction per test, rollback in t.Cleanup |
$this->travel(5)->minutes() | Injected clock or testing/synctest |
php artisan test --parallel | t.Parallel() (and packages run in parallel by default) |
php artisan test --coverage (needs Xdebug or PCOV) | -cover, -coverprofile, go tool cover |
Common misconceptions
| Belief | Reality |
|---|---|
t.Fatal stops the whole run | It stops the current test or subtest; others continue |
t.Fatal works from any goroutine | Only from the test goroutine; vet's testinggoroutine flags it |
go test ./... ran my tests | It may have printed (cached); use -count=1 to force a run |
Benchmarks run in normal go test | Only with -bench |
| One benchmark run is enough | Run -count=10 per side and use benchstat |
b.N benchmarks run the body once | The function is called several rounds with growing b.N |
t.Parallel speeds up everything | Only tests that opt in, within one package; Setenv/Chdir tests cannot |
defer in the parent runs after parallel subtests | It runs before them; use t.Cleanup |
| 100 % coverage means fully tested | It means every statement ran, not that results were checked |
| Integration tests cannot be covered | go build -cover + GOCOVERDIR since Go 1.20 |
Fuzz tests only run with -fuzz | Their seeds and committed crashers run in every go test |
rec.Code is always the real status | It can be 0 if the handler wrote nothing; use rec.Result() |
testify assert stops the test | assert continues, require stops |
-short skips slow tests by itself | Each test must check testing.Short() |
| Build-tagged tests are vetted by default | Without -tags they are not compiled at all |
time.Sleep makes a test wait reliably | It makes it slow and flaky; use a fake clock or synctest |
Cheat sheet
| Topic | Remember |
|---|---|
| Files and names | x_test.go; TestXxx(t *testing.T), BenchmarkXxx(b *testing.B), FuzzXxx(f *testing.F), ExampleXxx() |
| Failure | t.Errorf to continue, t.Fatalf when nothing else makes sense |
| Message | F(in) = got, want want; diffs as (-want +got) |
| Cases | Table + t.Run(tc.name, ...); select with -run 'Test/sub' |
| Parallel | t.Parallel() first line; no Setenv/Chdir; teardown in t.Cleanup |
| Helpers | Take testing.TB, call tb.Helper(), register tb.Cleanup |
| Fixtures | t.TempDir, t.Setenv, t.Chdir (1.24), t.Context (1.24) |
| Package setup | TestMain(m): flag.Parse, setup, code := m.Run(), teardown, os.Exit(code) |
| Selection | -short + testing.Short(); //go:build integration + -tags integration |
| Snapshots | testdata/*.golden + your own -update flag |
| HTTP | Handler: NewRequest + NewRecorder; client: NewServer + srv.Client(); 1.27: NewTestServer |
| Compare | cmp.Diff(want, got, cmpopts...); testify require = Fatal, assert = Error |
| Benchmarks | for b.Loop() {} (1.24); -bench . -benchmem -run '^$' |
| Statistics | -count=10 per side, benchstat old.txt new.txt |
| Profiles | -cpuprofile, -memprofile, go tool pprof -top |
| Coverage | -cover, -coverprofile=c.out, go tool cover -html; -race implies atomic |
| Integration coverage | go build -cover, GOCOVERDIR=dir, go tool covdata percent |
| Fuzzing | f.Add seeds, f.Fuzz(func(t, ...)), -fuzz Target -fuzztime 30s, commit crashers |
| Flakes | -count=N, -race, -shuffle=on, fake time, no real network |
| CI | go vet ./... + go test -race -count=1 -json ./... |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the difference between t.Error and t.Fatal, and when do you use each? Must-know
Answer
Answer: t.Error is Log plus Fail: the test is marked failed and keeps running. t.Fatal is Log plus FailNow: it marks the test failed and stops it with runtime.Goexit, so later checks do not run (other tests do). Use t.Error for independent checks so one run shows every problem, and t.Fatal when setup fails or a value is needed for the rest of the test. See t.Fatal vs t.Error.
2 — Why write table-driven tests with t.Run instead of one function per case? Must-know
Answer
Answer: The checking logic is written once, adding a case is one line, boundary cases become visible side by side, and each case gets a named subtest with its own pass/fail line that you can run alone with -run 'TestX/name'. Subtests can also run in parallel and have their own t.Fatal scope. See Table-driven tests.
3 — A parent test calls t.Run with parallel subtests and then closes a shared server with defer. What goes wrong? Important
Answer
Answer: t.Run returns as soon as a subtest calls t.Parallel, so the parent function returns and its defer closes the server before the paused subtests resume. Register the teardown with t.Cleanup, which runs after the test and all its subtests complete, or wrap the parallel subtests in an extra t.Run group. See Parallel tests.
4 — What does t.Helper() change, and why take testing.TB instead of *testing.T? Must-know
Answer
Answer: t.Helper() marks the function as a helper, so failure file and line point at the caller in the test rather than inside the helper. testing.TB is the interface shared by *T, *B and *F, so one helper (temporary config file, fake server) works in tests, benchmarks and fuzz tests. See Helpers.
5 — Why can a test that calls t.Setenv not call t.Parallel? Important
Answer
Answer: Environment variables (and the working directory changed by t.Chdir) belong to the whole process; a parallel test would see another test's value. The testing package therefore panics if Setenv or Chdir is used in a parallel test or a test with a parallel ancestor. Keep such tests sequential, or pass configuration explicitly instead of through the environment. See Fixtures.
6 — When is TestMain the right tool, and what are the two mistakes people make in it? Important
Answer
Answer: For expensive setup shared by the whole package test binary: a database container, a built binary, a large read-only fixture, a global leak check. The mistakes: relying on defer before os.Exit(code) (defers do not run, so tear down explicitly), and reading flags such as testing.Short() before calling flag.Parse(). Per-test setup belongs in helpers with t.Cleanup. See TestMain.
7 — How do httptest.NewRecorder and httptest.NewServer differ, and when do you use each? Must-know
Answer
Answer: NewRecorder is an in-memory ResponseWriter: with httptest.NewRequest you call handler.ServeHTTP directly, with no network, to test handlers and middleware; read status and headers from rec.Result(). NewServer starts a real HTTP server on a loopback port, for testing clients and the full stack; close it with t.Cleanup(srv.Close) and use srv.Client(). Go 1.27 adds NewTestServer, an in-memory network with automatic cleanup. See httptest.
8 — Why is for b.Loop() preferred over for range b.N since Go 1.24? Must-know
Answer
Answer: With b.N the benchmark function is called several rounds with growing b.N, so setup runs (and is timed) repeatedly unless you call b.ResetTimer, and an unused result may be removed by the compiler. b.Loop runs the function once per -count, resets the timer on its first call and stops it at the end, and keeps call arguments and results alive. See Benchmarks.
9 — Your benchmark is 4 % faster after a change. Is it? Important
Answer
Answer: You cannot tell from one run. Run the benchmark at least ten times before and after (-count=10, -run '^$') on the same idle machine and compare with benchstat old.txt new.txt; it reports the median, the spread and a p-value, and prints ~ when the difference is not statistically significant. See benchstat.
10 — What does -covermode=atomic do, and how do you measure coverage of an integration test that runs a built binary? Important
Answer
Answer: atomic counts how many times each block ran with atomic increments, correct with concurrent tests but the most expensive mode; it is the default when -race is on (otherwise set). For integration tests, build with go build -cover, run the binary with GOCOVERDIR=dir, then use go tool covdata percent -i=dir (or textfmt plus go tool cover). See Coverage and GOCOVERDIR.
11 — What happens to a fuzz test in a plain go test run, and what do you do with an input the fuzzer finds? Must-know
Answer
Answer: Without -fuzz, it runs as an ordinary test over its seed corpus: the f.Add values and the files in testdata/fuzz/FuzzXxx/. When -fuzz finds a failing input it minimises it and writes it to that directory; you fix the bug and commit the file, so every future go test replays it as a regression test. See Fuzzing.
12 — How do you test code that expires sessions after 30 minutes without waiting 30 minutes? Good to know
Answer
Answer: Inject a clock (now func() time.Time) and advance it in the test; or, from Go 1.25, run the test inside synctest.Test, where the time package uses a fake clock that jumps forward whenever every goroutine in the bubble is durably blocked, and use synctest.Wait to let background goroutines finish their step. See Time in tests.
13 — What usually makes a test flaky, and which go test flags help expose it? Good to know
Answer
Answer: Real time and elapsed-time asserts ("took less than 50 ms" breaks under load), order dependence, shared state between parallel tests, real network calls, and unordered output compared as ordered. Expose them with -count=N, -race, -shuffle=on (replay with the printed seed), and -cpu 1,4; record results with -json. See Flaky tests.
Glossary
| Term | Meaning |
|---|---|
go test | The go command that builds and runs test binaries per package |
testing.T | Handle passed to a test: failure, logging, subtests, fixtures |
testing.B | Handle passed to a benchmark: Loop, N, timers, metrics |
testing.F | Handle passed to a fuzz test: Add seeds, Fuzz target |
testing.TB | Interface common to T, B and F, used by helpers |
testing.M | Handle passed to TestMain; m.Run runs the tests and returns the exit code |
| Subtest | A named test started with t.Run, selectable with -run A/B |
t.Error / t.Fatal | Record a failure and continue / record it and stop the current test |
-run / -skip | Regexps selecting or excluding tests, split on / per subtest level |
-count | Repeat each test n times; -count=1 bypasses the test cache |
-bench | Regexp selecting benchmarks to run; none run without it |
-cover | Enable coverage and print the percentage per package |
| Vet subset | High-confidence go vet checks that go test runs before every test binary |
| Table-driven test | One test loop over a slice or map of cases |
t.Parallel | Marks a test to run alongside other parallel tests |
t.Helper | Marks a helper so failures report the caller's line |
t.Cleanup | Registers teardown that runs LIFO after the test and its subtests |
t.TempDir | Per-test temporary directory, removed afterwards |
t.Setenv / t.Chdir | Process-wide changes restored after the test; not allowed in parallel tests |
t.Context | Context canceled just before cleanup functions run (Go 1.24) |
TestMain | Optional per-package entry point around m.Run |
-short | Flag read by testing.Short() so long tests can shorten themselves |
| Build tags | //go:build constraints that include a file only with -tags or matching conditions |
testdata | Directory ignored by the go tool, for fixtures and corpora |
| Golden file | Reviewed expected output stored in testdata, refreshed with an -update flag |
| Example test | ExampleXxx function whose stdout is compared with its // Output: comment |
httptest.NewRecorder | In-memory ResponseWriter for handler tests |
httptest.NewRequest | Builds an incoming server request for handler tests |
httptest.NewServer | Real HTTP server on loopback for client tests |
httptest.NewTestServer | Go 1.27 test server on an in-memory network with automatic cleanup |
| Assertion library | Package of Equal-style helpers, e.g. testify assert/require |
go-cmp / cmp.Diff | Comparison library returning a -want +got diff |
b.Loop | Go 1.24 benchmark loop with automatic timer handling and keep-alive |
b.N | Iteration count; in the old style the loop bound, after Loop the total |
b.ReportAllocs / -benchmem | Report B/op and allocs/op |
b.ResetTimer | Zero the timer and allocation counters after setup |
testing.AllocsPerRun | Average allocations of a function, for allocation-budget tests |
| benchstat | golang.org/x/perf tool for statistical comparison of benchmark runs |
| Continuous benchmarking | Running benchmarks on every merge on fixed hardware and tracking results |
| pprof | Profile viewer (go tool pprof) for -cpuprofile/-memprofile output |
| Coverage profile | File from -coverprofile, read by go tool cover |
-covermode | set, count or atomic coverage counters |
GOCOVERDIR | Directory where go build -cover binaries write coverage data |
go tool covdata | Reads, converts and merges GOCOVERDIR data |
| Fuzzing | Coverage-guided mutation of inputs to find failures |
| Seed corpus | Inputs from f.Add and testdata/fuzz/FuzzXxx |
| Race detector | -race instrumentation reporting unsynchronised concurrent access |
testing/synctest | Go 1.25 package running a test in a bubble with a fake clock |
| Durably blocked | Blocked in a way only another goroutine in the same bubble can end |
| Flaky test | A test whose outcome varies on the same code |
| Test cache | Reuse of passing results in package list mode; bypass with -count=1 |
-json | Machine-readable test event stream (test2json) |
-shuffle | Randomised test order with a printed seed |
-failfast | Stop starting new tests after the first failure |
References
testingpackage source and documentation (Go 1.27): https://go.dev/src/testing/testing.gotestingbenchmarks (B.Loop,ReportAllocs,ResetTimer,RunParallel): https://go.dev/src/testing/benchmark.gotestingfuzzing (F.Add,F.Fuzz): https://go.dev/src/testing/fuzz.gotesting.AllocsPerRun: https://go.dev/src/testing/allocs.gotesting/synctest: https://go.dev/src/testing/synctest/synctest.gonet/http/httptestServer andNewTestServer: https://go.dev/src/net/http/httptest/server.gonet/http/httptestResponseRecorder: https://go.dev/src/net/http/httptest/recorder.gonet/http/httptestNewRequest: https://go.dev/src/net/http/httptest/httptest.gogo help test,go help testflag(cmd/go documentation): https://go.dev/src/cmd/go/alldocs.go- Go 1 release notes (testing package,
Bmethods): https://go.dev/doc/go1 - Go 1.1 release notes (
T.Skip,B.Skip): https://go.dev/doc/go1.1 - Go 1.2 release notes (test coverage): https://go.dev/doc/go1.2
- Go 1.4 release notes (
TestMain): https://go.dev/doc/go1.4 - Go 1.7 release notes (subtests,
httptest.NewRequest,ResponseRecorder.Result): https://go.dev/doc/go1.7 - Go 1.9 release notes (test helpers,
httptest.Server.Client): https://go.dev/doc/go1.9 - Go 1.10 release notes (test caching, vet during tests): https://go.dev/doc/go1.10
- Go 1.14 release notes (
Cleanup): https://go.dev/doc/go1.14 - Go 1.15 release notes (
TempDir): https://go.dev/doc/go1.15 - Go 1.17 release notes (
-shuffle,Setenv): https://go.dev/doc/go1.17 - Go 1.18 release notes (fuzzing): https://go.dev/doc/go1.18
- Go 1.20 release notes (integration coverage,
-skip): https://go.dev/doc/go1.20 - Go 1.21 release notes: https://go.dev/doc/go1.21
- Go 1.22 release notes (loop variables, coverage of packages without tests): https://go.dev/doc/go1.22
- Go 1.23 release notes: https://go.dev/doc/go1.23
- Go 1.24 release notes (
B.Loop,T.Context,T.Chdir, synctest experiment, vettests): https://go.dev/doc/go1.24 - Go 1.25 release notes (
testing/synctest,T.Attr,AllocsPerRunpanic): https://go.dev/doc/go1.25 - Go 1.26 release notes (
ArtifactDir,B.Loopinlining): https://go.dev/doc/go1.26 - Go 1.27 release notes (
stdversionin go test,NewTestServer,synctest.Sleep): https://go.dev/doc/go1.27 - Marcel van Lohuizen, "Using Subtests and Sub-benchmarks", The Go Blog, 3 October 2016: https://go.dev/blog/subtests
- Andrew Gerrand, "Testable Examples in Go", The Go Blog, 7 May 2015: https://go.dev/blog/examples
- Rob Pike, "The cover story", The Go Blog, 2 December 2013: https://go.dev/blog/cover
- Than McIntosh, "Code coverage for Go integration tests", The Go Blog, 8 March 2023: https://go.dev/blog/integration-test-coverage
- Coverage for integration tests (landing page): https://go.dev/doc/build-cover
- Katie Hockman, Jay Conrod, "Fuzzing is Beta Ready", The Go Blog, 3 June 2021: https://go.dev/blog/fuzz-beta
- Go fuzzing documentation: https://go.dev/doc/security/fuzz/
- Tutorial: Getting started with fuzzing: https://go.dev/doc/tutorial/fuzz
- Junyang Shao, "More predictable benchmarking with testing.B.Loop", The Go Blog, 2 April 2025: https://go.dev/blog/testing-b-loop
- Damien Neil, "Testing concurrent code with testing/synctest", The Go Blog, 19 February 2025: https://go.dev/blog/synctest
- Dmitry Vyukov, Andrew Gerrand, "Introducing the Go Race Detector", The Go Blog, 26 June 2013: https://go.dev/blog/race-detector
- Data Race Detector: https://go.dev/doc/articles/race_detector
- Russ Cox, "Profiling Go Programs", The Go Blog: https://go.dev/blog/pprof
- Diagnostics: https://go.dev/doc/diagnostics
- Go Wiki, TableDrivenTests: https://go.dev/wiki/TableDrivenTests
- Go Wiki, Go Test Comments: https://go.dev/wiki/TestComments
- Go Wiki, Code Review Comments: https://go.dev/wiki/CodeReviewComments
- Dave Cheney, "Prefer table driven tests", 7 May 2019: https://dave.cheney.net/2019/05/07/prefer-table-driven-tests
- benchstat source and documentation: https://raw.githubusercontent.com/golang/perf/master/cmd/benchstat/main.go
- golang.org/x/perf README: https://raw.githubusercontent.com/golang/perf/master/README.md
- go-cmp README: https://raw.githubusercontent.com/google/go-cmp/master/README.md
- go-cmp
DiffandEqual: https://raw.githubusercontent.com/google/go-cmp/master/cmp/compare.go - testify README (
assert,require,mock,suite): https://raw.githubusercontent.com/stretchr/testify/master/README.md - go-cmp v0.7.0
go.mod: https://raw.githubusercontent.com/google/go-cmp/v0.7.0/go.mod - testify v1.12.1
go.mod: https://raw.githubusercontent.com/stretchr/testify/v1.12.1/go.mod - go-cmp
cmpopts(IgnoreFields,IgnoreUnexported): https://raw.githubusercontent.com/google/go-cmp/master/cmp/cmpopts/ignore.go - go-cmp
cmpopts(EquateEmpty,EquateApprox,EquateApproxTime): https://raw.githubusercontent.com/google/go-cmp/master/cmp/cmpopts/equate.go - go-cmp
cmpopts(SortSlices): https://raw.githubusercontent.com/google/go-cmp/master/cmp/cmpopts/sort.go - protobuf-go
protocmp.Transform: https://raw.githubusercontent.com/protocolbuffers/protobuf-go/master/testing/protocmp/xform.go cmd/test2json(JSON event format,Actionvalues): https://go.dev/src/cmd/test2json/main.go- gotestsum README: https://raw.githubusercontent.com/gotestyourself/gotestsum/main/README.md
- goleak README: https://raw.githubusercontent.com/uber-go/goleak/master/README.md
- golangci-lint linters (
paralleltest,tparallel,thelper,testifylint,usetesting): https://golangci-lint.run/docs/linters/ - How to Write Go Code (testing section): https://go.dev/doc/code
- Laravel 13, Testing: https://laravel.com/docs/13.x/testing
- Laravel 13, HTTP Tests: https://laravel.com/docs/13.x/http-tests
- Laravel 13, Database Testing (
RefreshDatabase): https://laravel.com/docs/13.x/database-testing - Laravel 13, HTTP Client (
Http::fake): https://laravel.com/docs/13.x/http-client - Laravel 13, Mocking (
travel): https://laravel.com/docs/13.x/mocking - PHPUnit 12, Writing Tests (
DataProviderattribute): https://docs.phpunit.de/en/12.0/writing-tests-for-phpunit.html