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()
}

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。超級簡單的斷言和模擬。

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")
}
- 3 回答
- 0 關注
- 246 瀏覽
添加回答
舉報