亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修復 Go 測試輸出中的行號?

如何修復 Go 測試輸出中的行號?

Go
收到一只叮咚 2021-09-20 14:38:44
讓我們考慮這個簡單的測試代碼。(注意: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 上嘗試。


查看完整回答
反對 回復 2021-09-20
  • 2 回答
  • 0 關注
  • 213 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號