fre*_*rix 4 testing unit-testing go ginkgo gomega
我正在编写一个测试来断言函数因无效输入而发生恐慌,但 Ginkgo 将恐慌记录为失败,而不是按预期传递结果。
\nfunc ParseUnixTimeString(unixTimeString string) time.Time {\n i, err := strconv.ParseInt(unixTimeString, 10, 64)\n if err != nil {\n panic(fmt.Sprintf("could not parse time: %s", err.Error()))\n }\n return time.Unix(i, 0)\n}\n\nfunc TestFormat(t *testing.T) {\n gomega.RegisterFailHandler(ginkgo.Fail)\n ginkgo.RunSpecs(t, "Format Suite")\n}\n\nvar _ = ginkgo.Describe("Format Tests", func() {\n ginkgo.Describe("When formatting the date", func() {\n ginkgo.It("should panic if the time can't be formatted", func() {\n gomega.Expect(\n tools.ParseUnixTimeString("2314321432143124223432434")).To(gomega.Panic())\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n返回(压缩):
\n\xe2\x80\xa2! [PANICKED] [0.002 seconds]\n[It] should panic if the time can't be formatted\nTest Panicked\ncould not parse time: strconv.ParseInt: parsing "2314321432143124223432434": value out of range\nRan 1 of 1 Specs in 0.002 seconds\nFAIL! -- 0 Passed | 1 Failed | 0 Pending | 0 Skipped\nRun Code Online (Sandbox Code Playgroud)\n如何正确测试 Ginkgo/Gomega 中的恐慌?
\n从文档中:
如果 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())
})
})
Run Code Online (Sandbox Code Playgroud)