"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to efficiently test Panic situation in Go?

How to efficiently test Panic situation in Go?

Posted on 2025-04-19
Browse:516

How Can I Effectively Test for Panics in Go?

Testing for Panics in Go

When writing tests in Go, checking for panics can be a useful technique. However, unlike Java, Go does not have explicit syntax to handle panics selectively.

Consider the following example:

func f(t *testing.T) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
        }
    }()
    OtherFunctionThatPanics()
    t.Errorf("The code did not panic")
}

This code attempts to recover from any panic in OtherFunctionThatPanics using the recover function. However, it can be challenging to determine if the function panicked at all or if no panic occurred.

Solution

The recommended approach is to focus on testing for the absence of a panic. This can be achieved by inverting the logic and ensuring that a panic occurs if expected:

func TestPanic(t *testing.T) {
    defer func() {
        if r := recover(); r == nil {
            t.Errorf("The code did not panic")
        }
    }()

    // Code under test
    OtherFunctionThatPanics()
}

Additionally, more advanced testing frameworks such as Ginkgo or Gomega provide built-in matchers for asserting the occurrence of panics:

Expect(OtherFunctionThatPanics).To(Panic())

Utility Functions

For convenience, you can create a generic function for asserting panics:

func assertPanic(t *testing.T, f func()) {
    defer func() {
        if r := recover(); r == nil {
            t.Errorf("The code did not panic")
        }
    }()
    f()
}

This function can be used as follows:

func TestPanic(t *testing.T) {
    assertPanic(t, OtherFunctionThatPanics)
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3