Go tests
Table-driven is the default
One test function, a slice of cases, a subtest per case. Adding coverage means adding a struct literal.
func TestParseDuration(t *testing.T) {
tests := map[string]struct {
in string
want time.Duration
wantErr bool
}{
"seconds": {in: "30s", want: 30 * time.Second},
"compound": {in: "1h30m", want: 90 * time.Minute},
"zero": {in: "0", want: 0},
"empty": {in: "", wantErr: true},
"bad unit": {in: "5x", wantErr: true},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
t.Parallel()
got, err := ParseDuration(tc.in)
if tc.wantErr {
if err == nil { t.Fatal("want error, got nil") }
return
}
if err != nil { t.Fatalf("unexpected error: %v", err) }
if got != tc.want { t.Errorf("got %v, want %v", got, tc.want) }
})
}
}
A map keys cases by name and randomises order, which surfaces inter-case dependencies. Name cases after the behaviour, not case1. t.Run gives each one its own line in the output and lets you run one with -run TestParseDuration/bad_unit.
Failure messages carry the values
The reader is looking at CI output, not your screen.
// Good
t.Errorf("ParseDuration(%q) = %v, want %v", tc.in, got, tc.want)
// Bad — tells you nothing
t.Error("wrong result")
t.Error continues so you see every failure in the table; t.Fatal stops when continuing would panic or cascade. Use cmp.Diff from github.com/google/go-cmp for structs and slices — comparing large values by eye is wasted time:
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("mismatch (-want +got):\n%s", diff)
}
Standard library first
testing plus go-cmp covers nearly everything. An assertion framework buys assert.Equal and costs a dependency, a second vocabulary, and worse failure output for composite types. If a project already uses testify, match it — consistency wins over relitigating the choice.
Cleanup with t.Cleanup
Registers teardown next to setup, runs even when the test fails, and works inside helpers where defer would fire too early.
func newTestStore(t *testing.T) *Store {
t.Helper()
dir := t.TempDir() // removed automatically
s, err := Open(dir)
if err != nil { t.Fatalf("open store: %v", err) }
t.Cleanup(func() { s.Close() })
return s
}
t.Helper() makes failures report the caller's line, not the helper's. t.TempDir and t.Setenv handle their own cleanup — t.Setenv also blocks t.Parallel, by design.
Parallel tests
t.Parallel() is a signal that the test shares no mutable state — no global config, no fixed port, no shared temp file. Add it deliberately, and run with -race, which is where parallelism pays off by exposing real races.
HTTP with httptest
No real ports, no sleeps.
func TestHandler(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/orders/42", nil)
rec := httptest.NewRecorder()
NewHandler(fakeStore{}).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
}
For outbound calls, httptest.NewServer gives a real URL backed by your own handler.
Golden files
For large output — rendered templates, generated code, formatted reports — store the expected value in testdata/ and regenerate behind a flag.
var update = flag.Bool("update", false, "update golden files")
golden := filepath.Join("testdata", name+".golden")
if *update {
os.WriteFile(golden, got, 0o644)
}
want, err := os.ReadFile(golden)
testdata/ is ignored by the go tool, so anything can live there. Review golden diffs like code — a regenerated golden that nobody read is a test that asserts nothing.
Test the exported surface
Prefer package foo_test (an external test package) so tests exercise the API a caller sees. Drop into the internal package only for logic genuinely unreachable from outside — and consider whether that logic wants extracting instead.
Fuzzing and benchmarks
Fuzz anything that parses untrusted input; the corpus lives in testdata/fuzz and grows with every crash found.
func FuzzParse(f *testing.F) {
f.Add("30s")
f.Fuzz(func(t *testing.T, s string) {
_, _ = ParseDuration(s) // must not panic
})
}
Benchmarks loop to b.N and must not be optimised away — assign to a package-level sink. Use b.ReportAllocs(), and compare runs with benchstat rather than eyeballing one number.
What CI runs
go test -race -count=1 ./...
-count=1 defeats the test cache when you need a true rerun. Coverage is a map of untested code, not a target — chasing a percentage produces tests that assert nothing.