💻 Tech
Helper() function of testing.T helps make the test logs helpful by skipping the the function where it’s used from the testing logs. If a function is a helper that validates that test, and the specific line where it occurs won’t matter, call Helper() so that that function is skipped. One use case is if the helper function is a generic tester. If it fails, we are only interested in knowing what test/subtest/function called that helper function.
The first example below shows that the test failed at line 11. In contrast, the second example shows the test failed at line 16 after adding t.Helper() on the helper function.
First example:
package main
import (
"testing"
)
func helper(t *testing.T) {
// simulate some error
t.Fatalf("failed") // line 11
}
func TestMain1(t *testing.T) {
helper(t)
}
=== RUN TestMain1
prog_test.go:11: failed
--- FAIL: TestMain1 (0.00s)
FAIL
Program exited.
Second example:
package main
import (
"testing"
)
func helper(t *testing.T) {
t.Helper()
// simulate some error
t.Fatalf("failed")
}
func TestMain1(t *testing.T) {
helper(t) // line 16
}
=== RUN TestMain1
prog_test.go:16: failed
--- FAIL: TestMain1 (0.00s)
FAIL
Program exited.