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
To me, the solution below is easy to read and shows a maintainer the natural code flow under test.
func TestPanic(t *testing.T) {
// No need to check whether `recover()` is nil. Just turn off the panic.
defer func() { recover() }()
OtherFunctionThatPanics()
// Never reaches here if `OtherFunctionThatPanics` panics.
t.Errorf("did not panic")
}
For a more general solution, you can also do it like this:
func TestPanic(t *testing.T) {
shouldPanic(t, OtherFunctionThatPanics)
}
func shouldPanic(t *testing.T, f func()) {
defer func() { recover() }()
f()
t.Errorf("should have panicked")
}