I'm trying to customize the testing.T with my own assert method to lower the number of lines I'm writing. I tried the following, ended with an error: "wrong signature for TestCustom, must be: func TestCustom(t *testing.T)".
How can I make TestCustom use CustomTester interface with a new method, assert?
I don't want to use a 3rd-party framework.
custom_testing.go
type CustomTester struct {
testing.TB
}
func (t *CustomTester) assert(exp interface{}, act interface{}) {
if exp != act {
t.Errorf("expected: %v. got: %v\n", exp, act)
}
}
// I want testing package inject testing.T here
// But, by using my own wrapper: CustomTester struct with,
// my own assert method to get rid of using t as an argument,
// in each assert like: assert(t, exp, act)
func TestCustom(t *testing.TB) {
t.assert(3, len(foo))
}
NOTE: I also tried this, it works but, I don't want to pass t each time when I'm testing:
working_not_wanted.go
func assert(t *testing.TB, exp interface{}, act interface{}) {
if exp != act {
t.Errorf("expected: %v. got: %v\n", exp, act)
}
}
func TestCustom(t *testing.T) {
assert(t, 3, len(foo))
}
The Go testing framework executes test functions of a specific signature, and that signature takes a *testing.T. If you want to use the stdlib testing system, your test functions have to have the required signature.
You could wrap it with one line in every test function:
func MyTest(stdt *testing.T) {
// This line:
t := &CustomTester{stdt}
t.assert(true)
t.Error("An error done happened")
}
There are other ways to do it, but there is no way to have a testing function, run by go test, using the stdlib testing package, that takes anything other than *testing.T as its sole parameter.
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