go / expert
Snippet
Stack Frame Adjustment in Custom Test Helpers using t.Helper
Calling t.Helper() inside generic test assertion routines marks the executing function as a helper. When failure messages or stack traces are logged, Go automatically skips the helper's call frame to report the exact file and line number of the caller instead.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport ("testing")func assertEqual[T comparable](t testing.TB, got, want T) {t.Helper()if got != want {t.Fatalf("assertion failed: got %v, want %v", got, want)}}func TestCustomHelper(t *testing.T) {got := 42want := 42assertEqual(t, got, want)}
Breakdown
1
func assertEqual[T comparable](t testing.TB, got, want T) {
Defines a generic test helper function accepting the testing.TB interface to support both *testing.T and *testing.B.
2
t.Helper()
Registers the enclosing function as a test helper, unwinding its frame from call-stack error reporting.
3
t.Fatalf("assertion failed: got %v, want %v", got, want)
Logs the fatal error credited to the caller line location rather than inside assertEqual.