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