Home > Enterprise >  Ginkgo/Gomega Panic Test Fails
Ginkgo/Gomega Panic Test Fails

Time:06-16

I'm writing a test to assert that a function panics on invalid input, but Ginkgo records the panic as a failure instead of a passing result as expected.

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

Which returns (condensed):

•! [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

How do I properly test for panics in Ginkgo/Gomega?

CodePudding user response:

From the documentation:

succeeds if ACTUAL is a function that, when invoked, panics. ACTUAL must be a function that takes no arguments and returns no result -- any other type for ACTUAL is an error.

Notice that ACTUAL (the argument passed into Expect) is supposed to be a function.
What Gomega will do in this case, is invoke that function and catch the panic so it can assert on it.

To fix your particular example:

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