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 關注
- 199 瀏覽
添加回答
舉報