讓我們考慮這個簡單的測試代碼。(注意:assertSomething這里非常簡單,但通常我會為手頭的任務編寫一個更專業的幫助程序,它會查看多種情況并報告不止一種類型的錯誤。)package helloimport "testing"func TestFoo(t *testing.T) { assertSomething(t, 2+2 == 4) // line 6 assertSomething(t, 2+3 == 6) // line 7}func assertSomething(t *testing.T, expected bool) { if !expected { t.Error("Something's not right") // line 12 }}當我運行時go test,我得到以下信息:--- FAIL: TestFoo (0.00s) hello.go:12: Something's not rightFAILexit status 1FAIL kos/hello 0.008s我有兩個問題:1) 錯誤指向第 12 行 - 為什么?如何t.Error找出它是從哪一行調用的?2)在幫助器中,我想指定t.Error應該看起來更高的堆棧級別以確定要打印的行號,以便我會收到如下消息:--- FAIL: TestFoo (0.00s) hello.go:7: Something's not rightPython 允許我這樣做,例如,在warnings.warn("message", stacklevel=2)- 我將如何在這里實現等價物?
2 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
自 go 1.9 以來,情況發生了變化。
Helper()方法已添加到testing.T和testing.B。它旨在從測試助手中調用,例如assertSomething表明該函數是一個助手,我們對來自它的行號不感興趣。
package main
import "testing"
func TestFoo(t *testing.T) {
assertSomething(t, 2+2 == 4) // line 6
assertSomething(t, 2+3 == 6) // line 7
}
func assertSomething(t *testing.T, expected bool) {
if !expected {
t.Helper()
t.Error("Something's not right") // line 12
}
}
輸出包含正確的行號:
=== RUN TestFoo
--- FAIL: TestFoo (0.00s)
main.go:7: Something's not right
FAIL
您也可以在 Go Playground 上嘗試。
- 2 回答
- 0 關注
- 213 瀏覽
添加回答
舉報
0/150
提交
取消