testing - 使用testing.TB 来测试定制

标签 testing go tdd

我正在尝试使用我自己的 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/

相关文章:

javascript - 如何在使用 app.use(express.static ('public' )); 时测试 Express 应用程序

函数返回后不改变指针

带有测试驱动开发的 Javascript 编码指南

testing - 我们可以在拉丁语言中使用什么样的分割规则来编写测试用例?

angularjs - Angular 应用程序的最大圈复杂度

string - 将字符串转换为时间或创建时间常数

html - go - 调用 "html/template"时没有足够的参数。必须

asp.net - 对配置转换应用 TDD/单元测试?

ruby-on-rails - RSpec 和 Cucumber 有什么区别?

typescript - vscode-test - 调用 runTests 时出错