我正在撰寫一個測驗來斷言一個函式在無效輸入上發生恐慌,但 Ginkgo 將恐慌記錄為失敗而不是預期的通過結果。
func ParseUnixTimeString(unixTimeString string) time.Time {
i, err := strconv.ParseInt(unixTimeString, 10, 64)
if err != nil {
panic(fmt.Sprintf("could not parse time: %s", err.Error()))
}
return time.Unix(i, 0)
}
func TestFormat(t *testing.T) {
gomega.RegisterFailHandler(ginkgo.Fail)
ginkgo.RunSpecs(t, "Format Suite")
}
var _ = ginkgo.Describe("Format Tests", func() {
ginkgo.Describe("When formatting the date", func() {
ginkgo.It("should panic if the time can't be formatted", func() {
gomega.Expect(
tools.ParseUnixTimeString("2314321432143124223432434")).To(gomega.Panic())
})
})
回傳(濃縮):
?! [PANICKED] [0.002 seconds]
[It] should panic if the time can't be formatted
Test Panicked
could not parse time: strconv.ParseInt: parsing "2314321432143124223432434": value out of range
Ran 1 of 1 Specs in 0.002 seconds
FAIL! -- 0 Passed | 1 Failed | 0 Pending | 0 Skipped
如何正確測驗 Ginkgo/Gomega 中的恐慌?
uj5u.com熱心網友回復:
從檔案中:
如果 ACTUAL 是一個在呼叫時發生恐慌的函式,則成功。ACTUAL 必須是一個不帶引數且不回傳結果的函式——ACTUAL 的任何其他型別都是錯誤的。
請注意,ACTUAL(傳入的引數Expect)應該是一個函式。
在這種情況下,Gomega 會做的是呼叫該函式并捕獲恐慌,以便對其進行斷言。
要修復您的特定示例:
var _ = ginkgo.Describe("Format Tests", func() {
ginkgo.Describe("When formatting the date", func() {
ginkgo.It("should panic if the time can't be formatted", func() {
gomega.Expect(func(){
tools.ParseUnixTimeString("2314321432143124223432434")
}).To(gomega.Panic())
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/491627.html
