3 回答

TA贡献1841条经验 获得超3个赞
在最近的 Go 1.9(2017 年 8 月)中,您需要做的就是在函数中添加一行:
t.Helper()
这将在错误报告中使该函数静音,而您的实际错误行将是您期望的错误行(即调用此函数的错误行)
请参阅pkg/testing/#T.Helper(也可用于基准测试,但...不适用于被遗忘的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")
}
}
xuiqzy在 2021 年 2 月的评论中提到了testing.TB现在的界面Helper()。
请参阅提交 bc29313,2017 年 4 月,go1.9beta1,CL 38796以实施提案 4899。
我们建议添加一个新testing.TB方法,Helper将调用函数标记为测试助手。
记录测试消息时,包测试会忽略标记的辅助函数内的帧。
它打印非辅助函数内的第一个堆栈位置。

TA贡献1784条经验 获得超8个赞
这就是测试库的工作方式: https ://golang.org/src/testing/testing.go?h=Errorf#L285
通过使用runtime.Caller
.
您可以为自己的错误函数借用这段代码,这样可以更深入地查看堆栈。您可以替换整个Errorf
(即log
+ )或稍微不那么漂亮但更少的代码将使用类似before 调用fail
的东西打印整个堆栈。debug.PrintStack()
Errorf

TA贡献1844条经验 获得超8个赞
您可以在包中看到Fail函数: https ://github.com/stretchr/testify/blob/master/assert/assertions.go#L207assert
例子:
package main_test
import (
"fmt"
"github.com/stretchr/testify/assert"
"strings"
"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 {
callInfo := assert.CallerInfo()
errorTrace := strings.Join(callInfo, "\n\r\t\t\t")
t.Errorf("\r%s\r\tError Trace:\t%s\n"+
"\r\tError:%s\n\r",
"",
errorTrace,
fmt.Sprintf("Error:\nexpected: %s\nactual: %s", expected, actual),
)
}
default:
t.Errorf("Unsupported type")
}
}
func TestFoo(t *testing.T) {
AssertEqual(t, "hello", 21)
}
结果:
$ go test main_test.go
--- FAIL: TestFoo (0.00s)
Error Trace::22:main_test.go:15
main_test.go:30
Error:Error:
expected: hello
actual: %!s(int=21)
FAIL
FAIL command-line-arguments 0.002s
- 3 回答
- 0 关注
- 207 浏览
添加回答
举报