How to test that no exception is thrown?
In JUnit tests, your method is a little angel if no exception is thrown:
Feeling fancy with AssertJ? Here's a more fluent style:
Surefire ways to assert no exceptions
Expressing clear intention with assertDoesNotThrow
assertDoesNotThrow()
gives your test readability a steroid shotπ:
Keep test cases squat and muscular
Each test method should flex one single behavior. This keeps your test suite ripped and ready to fight off bugs πͺ:
Organize related assertions with assertAll
Break up is hard to do, thanks to assertAll()
:
Test a variety bag of inputs
Feed these to JUnit's Parameterized tests for thorough cross-examinations:
This effectively runs our assertDoesNotThrow()
test with different meal courses.
Playing catch with specific exceptions
Catching Exception
is like using a fishing net for a goldfishβalways be specific:
Testing lower layers for peace of mind
Test the lower layers of your code like your life depends on it. Would you read Lord of the Rings starting from the middle?
Using JUnit Rules for a clean court
When exceptions pull a Mata Hari, @Rule
dons the Judge's robe to rule them in or out across multiple tests.
Keeping tests neat and tidy
As Stitch says, "Test is family, family means no one gets left behind". Maintain yours like Lilo with JUnit and AssertJ.
Was this article helpful?