t.Helper() đánh dấu function hiện tại là helper function.
Khi test fail, Go runtime báo lỗi tại caller của helper (không phải bên trong helper), giúp dễ đọc output test hơn.
go
// Không có t.Helper() — lỗi báo tại dòng trong assertEq
func assertEq(t *testing.T, got, want int) {
if got != want {
t.Errorf("got %d, want %d", got, want) // line X in assertEq
}
}
// Có t.Helper() — lỗi báo tại nơi gọi assertEq
func assertEq(t *testing.T, got, want int) {
t.Helper() // <-- thêm dòng này
if got != want {
t.Errorf("got %d, want %d", got, want) // báo tại TestXxx line Y
}
}
// Pattern dùng trong test suite
func TestCalc(t *testing.T) {
assertEq(t, Add(2, 3), 5) // khi fail → báo dòng này
assertEq(t, Add(-1, 1), 0) // khi fail → báo dòng này
}Khi nào dùng: bất kỳ helper function nào nhận testing.T hoặc testing.B đều nên gọi t.Helper() ở dòng đầu tiên.
Đây là best practice idiomatic Go.
t.Helper() marks the current function as a test helper.
When a test fails, Go reports the error at the caller of the helper rather than inside the helper itself — making failure output much easier to read.
go
// Without t.Helper() — error points inside assertEq (unhelpful)
func assertEq(t *testing.T, got, want int) {
if got != want { t.Errorf("got %d, want %d", got, want) }
}
// With t.Helper() — error points to the test that called assertEq
func assertEq(t *testing.T, got, want int) {
t.Helper()
if got != want { t.Errorf("got %d, want %d", got, want) }
}Best practice: any function that accepts testing.T or testing.B and calls t.Error/t.Fatal should call t.Helper() as its first line.