如何包装 golang 测试函数

Emp*_*nes 4 go

我想包装标准的 golang 测试函数,例如t.Errorf来自 testing 包。

我试过这个:

// 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当测试失败时,我会得到辅助函数的函数和行号:

test_asserts.go:12: Error:
    expected: 
    actual: TestValue
Run Code Online (Sandbox Code Playgroud)

有没有办法在调用者的行号处出错?

Von*_*onC 5

在最近的 Go 1.9(2017 年 8 月)中,您需要做的就是在函数中添加一行:

t.Helper()
Run Code Online (Sandbox Code Playgroud)

这将使错误报告中的此函数静音,并且您的实际错误行将是您期望的(即调用此函数的那个​​)

请参阅pkg/testing/#T.Helper(也可用于Benchmark 测试,但......不适用于TB界面它被遗忘了!2021 年 2 月:可用,见下文)

// 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

xuiqzy2021 年 2 月的评论中提到testing.TB现在具有Helper().
请参阅提交 bc29313,2017 年 4 月,go1.9beta1CL 38796以实施提案 4899

我们建议添加一个新testing.TB方法,Helper将调用函数标记为测试助手。

在记录测试消息时,包测试会忽略标记的辅助函数内的帧。
它打印非辅助函数内的第一个堆栈位置。


Guy*_*ton 2

这就是测试库的做法: https://golang.org/src/testing/testing.go ?h=Errorf#L285

通过使用runtime.Caller

您可以借用此代码用于您自己的错误函数,该函数将更深入地查看堆栈。您可以替换整个Errorf(即log+ fail),或者稍微不那么漂亮但更少的代码只是使用类似于debug.PrintStack()before Calling 的内容打印整个堆栈Errorf