Skip to content

Instantly share code, notes, and snippets.

@wrunk
Last active January 25, 2021 23:34
Show Gist options
  • Save wrunk/4afea3d85cc9feb7fd8fcef5a8a98b5e to your computer and use it in GitHub Desktop.
Save wrunk/4afea3d85cc9feb7fd8fcef5a8a98b5e to your computer and use it in GitHub Desktop.
Golang unit test for panic scenario
func TestUserFail(t *testing.T) {
func() {
defer func() {
if r := recover(); r == nil {
t.Errorf("TestUserFail should have panicked!")
}
}()
// This function should cause a panic
CreateUser(12, "hello")
}()
}
@inancgumus
Copy link

inancgumus commented May 26, 2020

If I were you I wouldn't break the natural flow of the code under test, and do it like this:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment