I'd like to wrap standard golang test functions, such as t.Errorf
from the testing package.
I tried this:
// AssertEqual tests that the expected and actual values match
func AssertEqual(t *testing.T, expected interface{}, actual interface{}) {
switch expected.(type) {
case string:
if expected != actual {
t.Errorf("Error:\nexpected: %s\nactual: %s", expected, actual)
}
default:
t.Errorf("Unsupported type")
}
}
However, when a test fails, I get the function and line number of my helper function:
test_asserts.go:12: Error:
expected:
actual: TestValue
Is there a way to error at the line number of the caller?
With the recent Go 1.9 (August 2017), all you need to do is adding one line to your function:
t.Helper()
That will silence this function in error report, and your actual error line will be the one you expect (ie the one calling this function)
See pkg/testing/#T.Helper
(also available for Benchmark test, but... not for the TB
interface, where it was forgotten! Feb. 2021: this is available, see below)
// AssertEqual tests that the expected and actual values match
func AssertEqual(t *testing.T, expected interface{}, actual interface{}) {
t.Helper()
switch expected.(type) {
case string:
if expected != actual {
t.Errorf("Error:\nexpected: %s\nactual: %s", expected, actual)
}
default:
t.Errorf("Unsupported type")
}
}
xuiqzy mentions in the comments in Feb. 2021 the interface testing.TB
which now has Helper()
.
See commit bc29313, Apr. 2017, go1.9beta1, CL 38796 for implementing proposal 4899.
We propose to add a new
testing.TB
method,Helper
, which marks the calling function as a test helper.When logging test messages, package testing ignores frames that are inside marked helper functions.
It prints the first stack position inside a non-helper function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With