Someone came up with the idea of using
catch blocks in unit tests in Java:
The above is tempting, but doesn’t work. If the code under test didn’t throw, then no assertion would be performed.
So to fix it:
We add a
fail which makes it a complete test that the right thing was thrown, but that’s awkward.
How Many Ways To Test What’s Thrown?
All the ways I know:
- Do it the long way (above)
- Use the
@Test(expected = ... )annotation to check for a test ending in the right sort of exception
- Use the
ExpectedExceptionJUnit rule that allows you to define what you want your test to end with
- Use an assertion that catches the exception for you
Why the expected exception pattern doesn’t work
The rule, explained against the long way round approach here allows you to define the success criteria of a test function that ends in an exception.
This is attractive, but still wrong
What Ever Happened to Given/When/Then?
Tests should read from top to bottom with assertions at the end. The expected exception pattern has to define the assertions/expectations before the call which produces them, which is backwards.
Is succinct and reads forwards.