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
testing
doesn't really have the concept of "success," only failure. So your code above is about right. You might find this style slightly more clear, but it's basically the same thing.
func TestPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
// The following is the code under test
OtherFunctionThatPanics()
}
I generally find testing
to be fairly weak. You may be interested in more powerful testing engines like Ginkgo. Even if you don't want the full Ginkgo system, you can use just its matcher library, Gomega, which can be used along with testing
. Gomega includes matchers like:
Expect(OtherFunctionThatPanics).To(Panic())
You can also wrap up panic-checking into a simple function:
func TestPanic(t *testing.T) {
assertPanic(t, OtherFunctionThatPanics)
}
func assertPanic(t *testing.T, f func()) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
f()
}