Helpers and cleanup in Go
t.Helper fixes the reported line; t.Cleanup replaces teardown.
func mustEqual(t *testing.T, got, want string) {
t.Helper() // report the caller's line, not this one
if got != want {
t.Fatalf("got %q, want %q", got, want)
}
}
func TestWithFixture(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "runs.txt")
if err := os.WriteFile(path, []byte("104\n"), 0o600); err != nil {
t.Fatalf("write: %v", err)
}
t.Cleanup(func() { t.Log("finished with", path) })
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read: %v", err)
}
mustEqual(t, strings.TrimSpace(string(data)), "104")
}
How it works
- Without
t.Helper, failures point at the helper, not the test. t.Cleanupruns in reverse order after the test.t.TempDiris removed for you when the test ends.
Keywords and builtins used here
bytefuncifstring
The run, in numbers
- Lines
- 22
- Characters to type
- 536
- Tokens
- 157
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 94 seconds.
Step 3 of 4 in Writing tests, step 3 of 13 in Testing.