我正在尝试使用我自己的 assert
方法自定义testing.T,以减少我正在编写的行数。我尝试了以下操作,但出现错误:“TestCustom 签名错误,必须是:func TestCustom(t *testing.T)”
。
如何让 TestCustom
使用 CustomTester
接口(interface)以及新方法 assert
?
我不想使用第三方框架。
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))
}
注意: 我也尝试过这个,它有效,但是,我不想每次测试时都通过t
:
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))
}
最佳答案
Go 测试框架执行特定签名的测试函数,该签名采用 *testing.T
。如果您想使用stdlib测试系统,您的测试函数必须具有所需的签名。
您可以在每个测试函数中用一行将其包装起来:
func MyTest(stdt *testing.T) {
// This line:
t := &CustomTester{stdt}
t.assert(true)
t.Error("An error done happened")
}
还有其他方法可以做到这一点,但是没有办法拥有一个测试函数,由 go test
运行,使用 stdlib testing
包,它需要任何东西除了作为其唯一参数的 *testing.T
之外。
关于testing - 使用testing.TB 来测试定制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115117/