DEV Community

loading...

Go - Testing panic.

takakd profile image Takahiro Kudo ・1 min read

I usually test "panic" with below code.
Is it redundant?

// Testing if testFunc calls panic.
// e.g.
// IsTestCallPanic(func(){
//   <place test target here.>
// })
func IsTestCallPanic(testFunc func()) (ok bool) {
    defer func() {
        if err := recover(); err == nil {
            ok = false
        }
    }()
    ok = true
    testFunc()
    return
}

// Test of test.
func TestIsTestCallPanic(t *testing.T) {
    isCalled := IsTestCallPanic(func() {
        var i interface{}
        if i == nil {
            panic("Hi, panic.")
        }
    })
    if !isCalled {
        t.Errorf("failed.")
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide