使用 testing.TB 去测试自定义
Go testing customization with testing.TB
我正在尝试使用我自己的 assert
方法自定义 testing.T 以减少我正在编写的行数。我尝试了以下操作,但以错误结束:"wrong signature for TestCustom, must be: func TestCustom(t *testing.T)"
.
如何让 TestCustom
使用 CustomTester
接口和新方法 assert
?
我不想使用第 3 方框架。
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
作为唯一参数。
我正在尝试使用我自己的 assert
方法自定义 testing.T 以减少我正在编写的行数。我尝试了以下操作,但以错误结束:"wrong signature for TestCustom, must be: func TestCustom(t *testing.T)"
.
如何让 TestCustom
使用 CustomTester
接口和新方法 assert
?
我不想使用第 3 方框架。
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
作为唯一参数。