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

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

如何測試恐慌?

如何測試恐慌?

Go
慕的地8271018 2021-10-25 16:28:04
我目前正在考慮如何編寫測試來檢查給定的代碼片段是否出現恐慌?我知道 Go 用于recover捕獲恐慌,但與 Java 代碼不同,您無法真正指定在出現恐慌時應跳過哪些代碼或您有什么。所以如果我有一個功能:func f(t *testing.T) {    defer func() {        if r := recover(); r != nil {            fmt.Println("Recovered in f", r)        }    }()    OtherFunctionThatPanics()    t.Errorf("The code did not panic")}我真的不知道是OtherFunctionThatPanics恐慌后我們恢復了,還是函數根本沒有恐慌。如果沒有恐慌,我如何指定跳過哪些代碼,如果出現恐慌,我該如何指定執行哪些代碼?我如何檢查我們是否從中恢復了一些恐慌?
查看完整描述

3 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

testing沒有真正的“成功”的概念,只有失敗。所以你上面的代碼是正確的。您可能會發現這種風格更清晰一些,但它基本上是一樣的。


func TestPanic(t *testing.T) {

    defer func() {

        if r := recover(); r == nil {

            t.Errorf("The code did not panic")

        }

    }()


    // The following is the code under test

    OtherFunctionThatPanics()

}

我通常發現testing相當弱。您可能對Ginkgo等更強大的測試引擎感興趣。即使您不想要完整的 Ginkgo 系統,您也可以只使用它的匹配器庫Gomega,它可以與testing. Gomega 包括匹配器,例如:


Expect(OtherFunctionThatPanics).To(Panic())

您還可以將恐慌檢查包裝成一個簡單的函數:


func TestPanic(t *testing.T) {

    assertPanic(t, OtherFunctionThatPanics)

}


func assertPanic(t *testing.T, f func()) {

    defer func() {

        if r := recover(); r == nil {

            t.Errorf("The code did not panic")

        }

    }()

    f()

}


查看完整回答
反對 回復 2021-10-25
?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

如果您使用testify/assert,那么它是單行的:


func TestOtherFunctionThatPanics(t *testing.T) {

  assert.Panics(t, OtherFunctionThatPanics, "The code did not panic")

}

或者,如果您OtherFunctionThatPanics的簽名不是func():


func TestOtherFunctionThatPanics(t *testing.T) {

  assert.Panics(t, func() { OtherFunctionThatPanics(arg) }, "The code did not panic")

}

如果您還沒有嘗試過作證,那么也請查看testify/mock。超級簡單的斷言和模擬。


查看完整回答
反對 回復 2021-10-25
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

慣用標準庫解決方案

對我來說,下面的解決方案很容易閱讀,并向維護者展示了測試中的自然代碼流。此外,它不需要第三方軟件包。


func TestPanic(t *testing.T) {

    // No need to check whether `recover()` is nil. Just turn off the panic.

    defer func() { recover() }()


    OtherFunctionThatPanics()


    // Never reaches here if `OtherFunctionThatPanics` panics.

    t.Errorf("did not panic")

}

對于更通用的解決方案,您也可以這樣做:


func TestPanic(t *testing.T) {

    shouldPanic(t, OtherFunctionThatPanics)

}


func shouldPanic(t *testing.T, f func()) {

    defer func() { recover() }()

    f()

    t.Errorf("should have panicked")

}


查看完整回答
反對 回復 2021-10-25
  • 3 回答
  • 0 關注
  • 246 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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