登录
首页 >  Golang >  Go问答

在包装测试时显示原始源代码行:T.Errorf()

来源:stackoverflow

时间:2024-03-19 20:27:29 417浏览 收藏

在进行 Go 模块测试时,使用 t.Errorf() 报告错误会导致显示调用它的行,而不是原始源代码行。为了解决这个问题,可以使用 t.Helper() 将调用函数标记为测试帮助函数,这样它在打印文件和行信息时将被跳过。通过使用 t.Helper(),可以避免复制检查函数返回值的代码行,并可以正确显示原始源代码行,从而提高测试的可读性和可维护性。

问题内容

我正在为 go 模块编写一些测试。其中很多工作是检查函数是否返回正确的值。这是我当前正在做的事情的一个简单示例:

package foo

import (
    "reflect"
    "testing"
)

func foo() int {
    return 3
}

func testfoo(t *testing.t) {
    expected := 4
    actual := foo()

    if !reflect.deepequal(actual, expected) {
        t.errorf("actual=%v, expected=%v", actual, expected)
    }
}

单个测试可能包含许多此类相等性检查。为每个检查复制这 6 行会使测试难以阅读并且容易编写错误(根据我过去几天的经验)。所以我想我应该创建一个 assertequals() 函数来包装整个逻辑,类似于其他测试框架提供的功能(例如在 junit 的 org.junit.assert 中):

func testfoo(t *testing.t) {
    assertequal(t, 4, foo())
}

func assertequal(t *testing.t, actual interface{}, expected interface{}) {
    if !reflect.deepequal(actual, expected) {
        t.errorf("assertion failed: %v != %v", actual, expected)
    }
}

现在的问题是 errorf() 显然不会显示调用 assertequal() 的行,而是显示 errorf() 内部的调用 assertequal

=== RUN   TestFoo
    foo_test.go:28: Assertion failed: 4 != 3
--- FAIL: TestFoo (0.00s)

有没有办法解决这个问题,例如通过显示整个堆栈跟踪而不是仅显示调用 errorf() 的位置?

或者是否有更好的方法来避免重复这些代码行来检查函数的返回值?


正确答案


您可以使用t.Helper()

helper 将调用函数标记为测试帮助函数。当打印文件和行信息时,该功能将被跳过。 helper 可以从多个 goroutine 中同时调用。

所以你的辅助函数变成:

func assertequal(t *testing.t, actual interface{}, expected interface{}) {
    t.helper()
    if !reflect.deepequal(actual, expected) {
        t.errorf("assertion failed: %v != %v", actual, expected)
    }
}

输出:

=== RUN   TestFoo
    prog.go:13: Assertion failed: 4 != 3
--- FAIL: TestFoo (0.00s)
FAIL

其中 this playground 中的 prog.go:13 是主测试目标中调用 assertequal 而不是其中的 t.errorf 的行。

这只会更改测试输出中的文件行。如果您确实想要完整的堆栈跟踪,可以使用 runtime.caller,如 these two 线程中所述。

理论要掌握,实操不能落!以上关于《在包装测试时显示原始源代码行:T.Errorf()》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>