How to test panics?

前端 未结 7 475
别跟我提以往
别跟我提以往 2020-12-12 20:19

I\'m currently pondering how to write tests that check if a given piece of code panicked? I know that Go uses recover to catch panics, but unlike say, Java code, you can\'t

相关标签:
7条回答
  • 2020-12-12 20:56

    testing doesn't really have the concept of "success," only failure. So your code above is about right. You might find this style slightly more clear, but it's basically the same thing.

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

    I generally find testing to be fairly weak. You may be interested in more powerful testing engines like Ginkgo. Even if you don't want the full Ginkgo system, you can use just its matcher library, Gomega, which can be used along with testing. Gomega includes matchers like:

    Expect(OtherFunctionThatPanics).To(Panic())
    

    You can also wrap up panic-checking into a simple function:

    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()
    }
    
    0 讨论(0)
提交回复
热议问题