Last active
January 25, 2021 23:34
-
-
Save wrunk/4afea3d85cc9feb7fd8fcef5a8a98b5e to your computer and use it in GitHub Desktop.
Golang unit test for panic scenario
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I were you I wouldn't break the natural flow of the code under test, and do it like this:
For a more general solution, you can also do it like this: