How to assert that a certain exception is thrown in JUnit tests?
Exception testing is quick and concise using **assertThrows**
:
To easily check if an exception occurs, import the following for JUnit 5:
This effectively checks if your code is courteous enough to throw the expected exception.
Let's sink our teeth deeper into the topic, shall we?
JUnit 4: Oldie but Goodie
[Test @Test
annotation & ExpectedException
Rule]
Older versions of JUnit, particularly JUnit 4, offer a couple of gold nuggets for exception testing:
- @Test(expected=Exception.class): Great for simple scenarios. Just testing for the exception type? Say less.
- ExpectedException Rule: For nitpickers who need more granularity. Asserts exception type and message.
Asserting with try-catch
[Use try-catch for custom behaviors]
Sometimes, testing scenarios don't fit into standard frameworks. For those extra kick, try some good old try-catch:
JUnit 5: Shiny and New
[assertThrows
for JUnit 5]
JUnit 5 brings more goodies to the table. The assertThrows
function not only checks the exception but also allows for a closer examination:
Not Just Built-in Tools
[Assertion libraries: AssertJ & Google Truth]
Don't wear your JUnit blinders. Expand your toolbox with third-party libraries like AssertJ and Google Truth:
Be mindful about these while writing tests:
- Doing Less: Simple is better. Keep your tests clean and easy to read.
- Avoiding Overkill: Check the exception type and message. Forget stack traces unless you really, really need it.
- One Behavior to Test Them All: Don't test multiple exceptions in one method, unless you're fond of headaches.
Advanced maneuvers
We're not finished yet. Brace yourself!
Parameterized tests
[Use @ParameterizedTest
for multiple inputs and exceptions]
That's right, multiple inputs and exceptions per test. Thank JUnit 5 and parameterized tests:
Chain of causation
[Test cause of exception]
If your exception has a cause, you might want to verify it too. Take a closer look with assertThrows
:
Custom alert
[Add custom error messages]
Want to brighten up test failures? Throw in some custom error messages:
Was this article helpful?