DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

2 1

Go - Testing panic.

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

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay