Testing & Benchmarking
- Write idiomatic table-driven tests with subtests, parallelism and helpers that stay readable at 50 cases.
- Test HTTP handlers and clients with
httptest, and choose between fakes and mocks for ports. - Run real PostgreSQL in integration tests with testcontainers-go, and test time-dependent code deterministically with
testing/synctest. - Use fuzzing to find parser bugs, and benchmark correctly with
b.Loop,-benchmemandbenchstat. - Make the race detector, coverage and golden files part of CI.
TL;DR
- Table-driven tests +
t.Runare the Go default: one loop, named cases,t.Parallel()per case where safe. httptest.NewRecordertests handlers without a network;httptest.NewServerfakes a downstream (PSP, bank API) for client tests.- Prefer hand-written fakes for small ports; use generated mocks only to assert interactions. Keep fakes honest with a shared contract test that also runs against the real adapter.
- testcontainers-go gives each CI run a real PostgreSQL/Redis/Kafka;
testing/synctest(Go 1.25; experimental in 1.24) runs code under a fake clock so TTLs and timeouts test in microseconds. - Fuzzing (Go 1.18+) finds inputs you'd never write — e.g. a length field
"+0"accepted bystrconv.Atoi. - Benchmarks:
for b.Loop()(Go 1.24),-benchmem,-count=10, compare withbenchstat. Never trust a single run. - Always run
go test -racein CI. Coverage is a signal, not a target — but money-moving branches should all be exercised.
Why it matters
- A fee function that rounds half-down instead of half-up loses or gains a đồng per transaction — invisible in a demo, a reconciliation break across 10M transactions.
- A retry bug that generates a new idempotency key on each attempt causes double charges only when the PSP times out — exactly the path a unit test with a happy fake never exercises.
- Auditors and regulators increasingly ask for evidence of testing on critical changes (change management under PCI DSS, internal model-risk policies). A clear, fast test suite is that evidence.
- Concurrency bugs (data races in a balance cache) are found far cheaper by
-racein CI than by an incident review.
The broader strategy (pyramid, contract tests, what to test where) is in Testing Strategy; this page is the Go toolbox.
Core concepts
go test essentials
- Tests live in
_test.gofiles.package feetests internals (white-box);package fee_testtests only the exported API (black-box) — prefer black-box for domain packages. - Useful helpers:
t.Helper()(failures point at the caller),t.Cleanup(fn),t.TempDir(),t.Setenv(),t.Context()(Go 1.24; canceled when the test finishes),testing.Short()to skip slow tests under-short. t.Errorfrecords a failure and continues;t.Fatalfstops the current test. UseFatalwhen continuing makes no sense (setup failed, nil result).- Results are cached for unchanged packages;
-count=1forces a run.-shuffle=onrandomises test order to flush out hidden dependencies between tests.
Table-driven tests and subtests
// Fee returns a merchant fee in minor units: basis points, rounded half up,
// never below minFee.
func Fee(amount, bps, minFee int64) int64 {
f := (amount*bps + 5000) / 10000
return max(f, minFee)
}
func TestFee(t *testing.T) {
tests := []struct {
name string
amount int64
bps int64
minFee int64
want int64
}{
{"min fee applies to small amount", 10_000, 150, 1_000, 1_000},
{"percentage above min fee", 1_000_000, 150, 1_000, 15_000},
{"rounds half up", 100, 50, 0, 1}, // 0.5 -> 1
{"rounds down below half", 10_030, 150, 0, 150}, // 150.45 -> 150
{"zero amount", 0, 150, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := Fee(tt.amount, tt.bps, tt.minFee); got != tt.want {
t.Errorf("Fee(%d, %d, %d) = %d, want %d",
tt.amount, tt.bps, tt.minFee, got, tt.want)
}
})
}
}
Guidelines:
- Case names are sentences; run one with
go test -run 'TestFee/rounds_half_up'(spaces become underscores). - Error messages say got vs want with inputs, so a CI log is enough to debug.
- For structs, compare with
github.com/google/go-cmp/cmp.Diff(want, got)— readable diffs, options to ignore fields like timestamps. - Boundary cases are where money bugs live: zero, one minor unit, max
int64, rounding at exactly .5, currency with no minor unit (VND, JPY), negative refunds.
t.Parallel()
A test that calls t.Parallel() pauses until its parent's sequential part has finished, then runs alongside other parallel tests (bounded by -parallel, default GOMAXPROCS).
- Before Go 1.22, the closure above would capture the loop variable
ttshared by all iterations — every parallel subtest ran the last case. Since 1.22 (withgo 1.22+ ingo.mod) each iteration has its owntt. - Parallel tests must not share mutable state: global config, the same database rows,
t.Setenv(which panics in parallel tests). - Parallel subtests finish after the parent function body returns; put teardown in
t.Cleanup, notdefer, so it waits for them.
Testing HTTP with httptest
Handlers — no network, just a recorder:
func TestCreatePayment_InsufficientFunds(t *testing.T) {
svc := &fakePayments{err: &payment.InsufficientFundsError{
AccountID: "acc_7", Available: 5_000, Requested: 10_000,
}}
h := api.NewHandler(svc, slog.New(slog.DiscardHandler)) // DiscardHandler: Go 1.24
req := httptest.NewRequest(http.MethodPost, "/payments",
strings.NewReader(`{"amount":10000,"currency":"VND","idempotency_key":"k1"}`))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status = %d, want 422; body: %s", rec.Code, rec.Body)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" {
t.Errorf("content-type = %q", ct)
}
}
Clients — a real server on localhost that misbehaves on purpose:
func TestPSPClient_RetryKeepsIdempotencyKey(t *testing.T) {
var (
mu sync.Mutex
keys []string
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
keys = append(keys, r.Header.Get("Idempotency-Key"))
n := len(keys)
mu.Unlock()
if n == 1 {
w.WriteHeader(http.StatusServiceUnavailable) // first attempt fails
return
}
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, `{"status":"captured"}`)
}))
t.Cleanup(srv.Close)
c := psp.NewClient(srv.URL, srv.Client())
if err := c.Capture(t.Context(), "pay_42"); err != nil {
t.Fatalf("Capture: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(keys) != 2 || keys[0] == "" || keys[0] != keys[1] {
t.Fatalf("idempotency keys = %q, want two identical non-empty keys", keys)
}
}
This test encodes the business rule that matters — retries reuse the key — not implementation details.
Fakes, stubs and mocks
| Double | What it is | Good for | Risk |
|---|---|---|---|
| Stub | Returns canned answers | Driving a code path (PSP returns "declined") | None much |
| Fake | Working lightweight implementation (in-memory repo) | Most use-case tests; fast and realistic | Drifts from the real adapter |
| Mock | Records calls and verifies expectations (gomock, mockery, testify/mock) | Asserting an interaction is the behaviour (an audit event was published once) | Tests coupled to call order and arguments; brittle refactors |
| Real dependency in a container | The real thing | Adapters: SQL, migrations, locking | Slower; needs Docker |
Prevent fake drift with a contract test suite run against both implementations:
// RunRepoContract is called from the fake's tests and the Postgres adapter's tests.
func RunRepoContract(t *testing.T, newRepo func(t *testing.T) payment.Repository) {
t.Run("duplicate idempotency key is rejected", func(t *testing.T) {
repo := newRepo(t)
p := payment.Payment{ID: "p1", IdempotencyKey: "k1", Amount: 100, Currency: "VND"}
if err := repo.Insert(t.Context(), p); err != nil {
t.Fatal(err)
}
p.ID = "p2"
err := repo.Insert(t.Context(), p)
if !errors.Is(err, payment.ErrDuplicateRequest) {
t.Fatalf("second insert: got %v, want ErrDuplicateRequest", err)
}
})
// ... more behaviours every implementation must share
}
Integration tests with testcontainers-go
//go:build integration
package postgres_test
var dsn string
func TestMain(m *testing.M) {
ctx := context.Background()
pg, err := tcpostgres.Run(ctx, "postgres:16-alpine",
tcpostgres.WithDatabase("ledger"),
tcpostgres.WithUsername("test"),
tcpostgres.WithPassword("test"),
tcpostgres.BasicWaitStrategies(),
)
if err != nil {
log.Fatalf("start postgres: %v", err)
}
dsn, err = pg.ConnectionString(ctx, "sslmode=disable")
if err != nil {
log.Fatalf("dsn: %v", err)
}
if err := migrate(ctx, dsn); err != nil { // run the real migrations
log.Fatalf("migrate: %v", err)
}
code := m.Run()
_ = testcontainers.TerminateContainer(pg)
os.Exit(code)
}
func TestPostgresRepo_Contract(t *testing.T) {
RunRepoContract(t, func(t *testing.T) payment.Repository {
return newRepoInFreshSchema(t, dsn) // schema per test, dropped in t.Cleanup
})
}
(tcpostgres is github.com/testcontainers/testcontainers-go/modules/postgres.)
- One container per package (
TestMain), isolation per test (fresh schema or database, or a transaction rolled back inCleanup). - Use the same major version as production and run your real migrations — integration tests are where
SELECT ... FOR UPDATE, unique constraints and isolation levels get verified (see Transactions & Isolation Levels). - Gate with a build tag (
go test -tags=integration ./...) ortesting.Short()so the unit loop stays fast.
Deterministic time with testing/synctest
Code with TTLs, timeouts, retries and tickers is painful to test with real sleeps. testing/synctest (experimental in Go 1.24, stable in Go 1.25) runs a function in a bubble with a fake clock: time advances only when every goroutine in the bubble is blocked, so time.Sleep(time.Hour) returns instantly and deterministically.
func TestIdempotencyKeyExpires(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cache.NewTTL[string, int](time.Minute)
c.Set("idem-123", 1)
time.Sleep(59 * time.Second) // fake clock: no real waiting
if _, ok := c.Get("idem-123"); !ok {
t.Fatal("expired too early")
}
time.Sleep(2 * time.Second)
if _, ok := c.Get("idem-123"); ok {
t.Fatal("should have expired after 61s")
}
})
}
synctest.Wait() blocks until all other goroutines in the bubble are durably blocked — useful to assert "the retry goroutine is now waiting on its backoff timer". The alternative is injecting a Clock interface, which is still good design for business rules like cut-off times.
Fuzzing
Fuzzing generates inputs, guided by coverage, looking for panics or failed assertions. Ideal targets are parsers and decoders of untrusted input: EMV/VietQR payloads, ISO 8583 messages, CSV settlement files, webhook signatures.
// Field is one EMVCo-style TLV element: 2-digit ID, 2-digit length, value.
type Field struct {
ID string
Value string
}
func FuzzParseTLV(f *testing.F) {
f.Add("000201010212") // payload format "01", point of initiation "12"
f.Add("5303704") // transaction currency 704 = VND
f.Fuzz(func(t *testing.T, s string) {
fields, err := tlv.Parse(s)
if err != nil {
return // rejecting input is fine; panicking is not
}
if got := tlv.Encode(fields); got != s {
t.Fatalf("round trip: Encode(Parse(%q)) = %q", s, got)
}
})
}
go test -run='^$' -fuzz=FuzzParseTLV -fuzztime=60s ./internal/tlv
A real result: with a parser that read the length using strconv.Atoi(s[2:4]), this fuzzer failed in a fraction of a second on input "00+0" — Atoi accepts a leading +, so the parser accepted a payload no conforming encoder would produce. The fix was to require two ASCII digits. Failing inputs are saved under testdata/fuzz/FuzzParseTLV/ and replayed by every plain go test run from then on — commit them as regression tests.
Good fuzz properties: no panics; round-trip (Encode(Parse(x)) == x for canonical input); invariants (parsed amount is never negative, CRC validates); differential (new parser agrees with the old one).
Benchmarks
func BenchmarkFee(b *testing.B) {
for b.Loop() { // Go 1.24+: setup above runs once; results kept alive
Fee(1_000_000, 150, 1_000)
}
}
func BenchmarkEncodeEvent(b *testing.B) {
evt := sampleEvent() // setup excluded from timing automatically with b.Loop
b.ReportAllocs()
for b.Loop() {
if _, err := encodeEvent(evt); err != nil {
b.Fatal(err)
}
}
}
b.Loop (Go 1.24) replaces for i := 0; i < b.N; i++: it runs the benchmark function body once (so setup isn't repeated), times only the loop, and keeps call arguments and results alive so the compiler can't optimise the work away — the classic b.N pitfall.
Comparing changes correctly:
go test -run='^$' -bench=EncodeEvent -benchmem -count=10 ./internal/events > old.txt
# make the change
go test -run='^$' -bench=EncodeEvent -benchmem -count=10 ./internal/events > new.txt
go run golang.org/x/perf/cmd/benchstat@latest old.txt new.txt
benchstat reports medians, variation and whether a difference is statistically significant ("~" means no detectable change). Run on a quiet machine with the laptop plugged in; don't compare numbers from different machines. b.RunParallel measures contention (locks, pools) under concurrent load. More profiling discipline in Profiling & Performance.
Race detector
go test -race ./... instruments memory accesses (ThreadSanitizer-based) and reports conflicting unsynchronised accesses with both stacks.
- It only detects races that actually happen during the run — tests must exercise concurrency (parallel subtests,
-count, concurrent clients). - Overhead per the Go docs: memory ≈5–10×, execution time ≈2–20×. Too costly for all of production, fine for CI and a canary or load-test build.
- A race report is always a bug, even if the test passed.
Coverage
go test -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1 # total
go tool cover -html=cover.out # browse uncovered branches
-coverpkg=./...counts coverage of packages exercised indirectly (e.g. domain code hit through handler tests).- Since Go 1.20,
go build -coverproduces instrumented binaries; run them withGOCOVERDIR=/tmp/covduring end-to-end tests and merge withgo tool covdata. - Use coverage to find untested branches in money paths, not to hit a vanity percentage. 85% coverage with the rounding branch untested is worse than 70% with every posting rule exercised.
Golden files
For large outputs — statement CSVs, ISO 20022 XML, API responses — compare against a reviewed file in testdata/:
var update = flag.Bool("update", false, "rewrite golden files")
func TestStatementCSV(t *testing.T) {
got := renderStatement(fixtureTransactions())
golden := filepath.Join("testdata", "statement_2024_06.golden.csv")
if *update {
if err := os.WriteFile(golden, got, 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(string(want), string(got)); diff != "" {
t.Errorf("statement mismatch (-want +got); rerun with -update and review:\n%s", diff)
}
}
The diff of the golden file in a PR is the review of the output change. Keep output deterministic: sort map keys, fix clocks and IDs.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Table-driven tests | Compact, easy to add cases | Complex setups get awkward in tables | Pure functions, mapping, validation |
| Hand-written fakes | Fast, readable, realistic behaviour | Can drift without contract tests | Ports with a few methods |
| Generated mocks | Precise interaction assertions | Brittle, couple tests to implementation | The interaction is the requirement |
| testcontainers | Real engines and SQL semantics | Docker needed; seconds of startup | Repositories, migrations, locking |
synctest | Deterministic time, no sleeps | Bubble rules (no real I/O waits inside) | TTLs, retries, timeouts, tickers |
| Fuzzing | Finds unknown-unknowns | CPU time; needs good properties | Parsers, decoders, codecs |
| Golden files | Reviewable large outputs | Easy to rubber-stamp -update | Reports, generated docs, XML/CSV |
| Coverage targets | Simple metric | Gamed easily | As a review aid, not a gate on its own |
In practice
A CI job for a payments service typically runs:
go vet ./...
go test -race -shuffle=on -count=1 ./... # unit + contract (fakes)
go test -race -tags=integration -count=1 ./... # with testcontainers
go test -run='^$' -fuzz=FuzzParseTLV -fuzztime=30s ./internal/tlv # short fuzz per parser
Plus a nightly job that fuzzes longer and runs benchmarks with benchstat against main.
- Put shared test helpers in an
internal/testutilpackage; keep themt.Helper()-annotated. - Quarantine flaky tests immediately (skip with an issue link) and fix the root cause — usually shared state, real time, or ordering assumptions.
- Test behaviour at the port boundary: "a declined authorization leaves the order in
PAYMENT_FAILEDand publishes one event", not "the repo'sSavewas called with these arguments".
Common pitfalls
- Parallel subtests sharing state — a global config or the same DB rows; flaky failures that disappear with
-p 1. - Loop-variable capture in parallel subtests on modules with
gobelow 1.22. deferteardown with parallel subtests — runs before the subtests finish; uset.Cleanup.- Real
time.Sleepin tests — slow and flaky; usesynctestor an injected clock. - Mocks asserting every call — refactoring the repository breaks 40 tests that don't care.
- Fakes without contract tests — the fake allows duplicate idempotency keys; production doesn't.
- Benchmarks without
-countandbenchstat— "3% faster" that is noise. - Optimised-away benchmark bodies with the
b.Nstyle — impossibly fast ns/op. Useb.Loop. - Skipping
-racebecause it's slow — the race shows up in production instead. -updateblindly on golden files — the regression is committed as the new truth.
Interview angle
Questions: "How do you structure tests in Go?", "Fakes or mocks?", "How do you test code that talks to PostgreSQL?", "How do you test a retry with backoff without waiting?", "Have you used fuzzing?", "How do you know an optimisation helped?", "What does the race detector catch and miss?"
A strong answer: table-driven + subtests + t.Parallel; fakes for ports with contract tests against real adapters in testcontainers; httptest for both sides of HTTP; synctest or an injected clock for time; fuzzing on parsers with round-trip properties; b.Loop + -benchmem + benchstat; -race in CI with the caveat that it only sees executed races. Tie it to money: rounding boundaries, idempotent retries, concurrent postings.
Follow-ups: "How do you keep integration tests fast?" (container per package, schema per test, parallelism), "What would you never mock?" (the database in repository tests; your own domain logic), "How do you test graceful shutdown?"
Red flags: only end-to-end tests, mocks of everything including domain types, no race detector, benchmark claims from one run.
Self-check
1. Why should teardown for parallel subtests go in t.Cleanup rather than defer in the parent?
Parallel subtests are paused and resumed after the parent's function body returns, so a defer in the parent runs before they execute — tearing down the database they need. t.Cleanup functions run after the test and all its subtests complete.
2. What business rule does the httptest.NewServer PSP test verify, and why is it more valuable than a mock-based test?
That a retry after a 503 reuses the same idempotency key, preventing double charges. It exercises the real client code — HTTP, headers, retry loop — against a server behaving like a flaky PSP, rather than asserting which internal method was called, so it survives refactors and catches real bugs.
3. How do you stop an in-memory fake repository from drifting from PostgreSQL behaviour?
Write a contract test suite that takes a constructor and runs the same behavioural tests (duplicate key rejection, not-found errors, ordering) against both the fake and the real adapter — the latter in testcontainers. A behaviour difference fails one of the two runs.
4. What does testing/synctest change about time, and when does time advance inside the bubble?
Inside synctest.Test, goroutines use a fake clock starting at a fixed instant. Time advances only when every goroutine in the bubble is durably blocked (sleeping, waiting on timers or bubble channels); it jumps to the next timer. So hour-long sleeps return instantly and deterministically.
5. Give three properties you could fuzz for a settlement CSV parser.
No panic on any input; round-trip (encoding parsed rows reproduces canonical input); invariants (amounts parse to non-negative integers in minor units, the trailer count equals the number of rows, totals reconcile). A differential property against the legacy parser is a fourth.
6. Scenario: a PR claims "JSON encoding is 12% faster". What do you ask for before approving?
benchstat output from -count=10 (or more) runs of old vs new on the same machine, including -benchmem allocation numbers and the p-value; confirmation the benchmark uses b.Loop (or otherwise prevents dead-code elimination) and representative payloads; and ideally a CPU profile showing where the time moved.
7. What are the race detector's blind spots?
It only reports races that occur in the executed interleavings, so untested concurrent paths go unseen; it doesn't detect deadlocks or logical races (check-then-act with proper locking but wrong granularity); and its overhead makes it impractical for full production traffic.
Exercise
For a transfer package:
- Table-test
Feeand aSplitfunction (allocate an amount across N parties summing exactly), including rounding boundaries and VND (no minor unit). - Write an in-memory and a PostgreSQL
Repository, plus a contract suite run against both (PostgreSQL via testcontainers behind-tags=integration). - Test a PSP client with
httptest.NewServer: 503 then 200 must reuse the idempotency key; a 30 s hang must respect a 2 s context deadline — test the timeout withsynctest. - Fuzz a TLV/QR parser for 5 minutes; commit any crashers as regression seeds.
- Benchmark event encoding before and after introducing a
sync.Pool; reportbenchstatoutput and decide whether to keep it. - Wire everything into a CI script with
-race -shuffle=on.
Done when: CI is green, the integration suite runs in under a minute, and you can show the benchstat table that justified the pool decision. More guided practice in Hands-on Go Labs.
Further reading
testingpackage documentation — subtests,Cleanup,Context,B.Loop, fuzzing.- Go blog: "Using Subtests and Sub-benchmarks" (Marcel van Lohuizen).
- Go blog: "More predictable benchmarking with testing.B.Loop".
- Go blog: "Testing concurrent code with testing/synctest".
- Go documentation: "Go Fuzzing" tutorial and reference (go.dev/doc/fuzz).
- Go documentation: "Data Race Detector" (go.dev/doc/articles/race_detector).
- Go blog: "Code coverage for Go integration tests".
- testcontainers-go documentation (golang.testcontainers.org) — modules for PostgreSQL, Redis, Kafka.
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — testing chapter.
Related
- Testing Strategy — the pyramid and what to test at each level.
- Profiling & Performance — from a benchmark to a profile to a fix.
- Interfaces & Composition — small ports make fakes trivial.
- Error Handling — testing error mapping and wrapped errors.
- Project Layout & Clean Architecture in Go — where tests and test helpers live.
- Idempotency & Exactly-Once — the property the retry test protects.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).