go / intermediate
Snippet
Writing Reusable Test Helpers with the Testing TB Interface
The `testing.TB` interface is implemented by both `*testing.T` and `*testing.B`. Accepting `testing.TB` allows your helper functions to be shared between unit tests and benchmarks. Calling `tb.Helper()` marks the function as a helper, shifting file/line reporting in failures back to the caller.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mainimport ("os""testing")func createTempFile(tb testing.TB, content string) string {tb.Helper()tmpFile, err := os.CreateTemp("", "test_db_*.json")if err != nil {tb.Fatalf("failed to create temp file: %v", err)}tb.Cleanup(func() {os.Remove(tmpFile.Name())})if _, err := tmpFile.WriteString(content); err != nil {tb.Fatalf("failed to write test data: %v", err)}tmpFile.Close()return tmpFile.Name()}
Breakdown
1
func createTempFile(tb testing.TB, content string) string {
Accepts testing.TB, allowing the helper to be used in both tests and benchmarks.
2
tb.Helper()
Marks this function as a test helper so failure logs report the caller's line number.
3
tb.Cleanup(func() {
Registers a cleanup function that runs automatically when the test finishes, avoiding resource leaks.