Go

Test Helpers with t.Helper()

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you extract a verification routine into a helper, call `t.Helper()` so failure messages point to the CALLER line — not the helper line. One line, much better diagnostics.
Go
Raw
package main

import "testing"

// Without t.Helper(), all failures would point HERE — useless.
// With it, the line shown is whichever test called assertEqual.
func assertEqual[T comparable](t *testing.T, got, want T, label string) {
    t.Helper()
    if got != want {
        t.Errorf("%s: got %v, want %v", label, got, want)
    }
}

func TestSomething(t *testing.T) {
    assertEqual(t, 1+1, 2, "addition")          // shows THIS line on failure
    assertEqual(t, len("hi"), 2, "string length")

    // Subtests benefit too
    t.Run("multiplication", func(t *testing.T) {
        assertEqual(t, 3*4, 12, "mul")
    })
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.