How to test panics?

前端 未结 7 525
别跟我提以往
别跟我提以往 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:33

    Succinct Way

    To me, the solution below is easy to read and shows a maintainer the natural code flow under test.

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

    For a more general solution, you can also do it like this:

    func TestPanic(t *testing.T) {
        shouldPanic(t, OtherFunctionThatPanics)
    }
    
    func shouldPanic(t *testing.T, f func()) {
        defer func() { recover() }()
        f()
        t.Errorf("should have panicked")
    }
    

提交回复
热议问题