Create test helpers and cleanup
Create test helpers and cleanup
A test helper is an ordinary function shared by tests. Call t.Helper inside it so test failures report the relevant caller rather than the helper frame. Register cleanup with t.Cleanup as soon as a resource is acquired. Cleanup callbacks execute after the test and its subtests complete, in reverse registration order.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Add(a, b int) int { return a + b }
--- calc_test.go ---package calc
import "testing"
func check(t *testing.T, got, want int) { t.Helper() if got != want { t.Errorf("got %d want %d", got, want) }}func TestAdd(t *testing.T) { check(t, Add(2, 3), 5); check(t, Add(-2, 2), 0) }The helper receives the test handle and performs the comparison. Helper affects source locations, not pass/fail behavior. Keep the helper specific enough to report meaningful actual and expected values.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestAddObserve cleanup order
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
--- calc_test.go ---package calc
import "testing"
func TestCleanup(t *testing.T) { order := "" t.Cleanup(func() { if order != "BA" { t.Errorf("order = %q", order) } }) t.Cleanup(func() { order += "A" }) t.Cleanup(func() { order += "B" })}B runs before A, and the final check runs last. Unlike a defer inside a setup helper, Cleanup remains registered until the owning test and its subtests finish. It is not a guarantee against process termination. Prefer per-test state to shared globals.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestCleanupTry it locally
Write an assertString helper using t.Helper and test a function Prefix that adds "id:" to a string. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 03: Create test helpers and cleanup
Check the lesson objective before moving on.
What is t.Helper for?
In what order do Cleanup callbacks execute?