Almost all of my JUnit tests are written with the following signature:
public void testSomething() throws Exception
My reasoning is that I can focus on what I'm testing rather than exception handling which JUnit appears to give me for free. But am I missing anything by doing this? Is it against best practice? Would I gain anything by explicitly catching specific exceptions in my test and then fail()'ing on them?
The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype.
An exception should be thrown when a function experiences a failure, i.e., an error. A function is a unit of work, and failures should be viewed as errors or otherwise based on their impact on functions.
In general, if you are testing a case where you do not expect an Exception to occur, then I would just let the test method throw Exception as you have illustrated since it will nicely differentiate between Failing test cases (they do not pass one of your assertions) and Error test cases (they cause an unexpected Exception). The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown.
On the other hand, if you are writing a test that is supposed to trigger an exception, then you either want to use the @Test(expected=IllegalArgumentException.class)
variant of the JUnit 4 annotation, or the more common JUnit 3 idiom of:
try { target.someMethodToTest(); fail("Should have gotten an exception"); } catch (IllegalStateException ise) { //expected, it's all good }
Do NOT catch and fail -- you will lose valuable information. Let all exceptions fly right on out. This means you need to add each checked exception your signature that can be thrown. However, I'd advise you not to take the lazy way out and blindly use throws Exception
as a matter of habit. This excuses you from ever even having to think about how your API really behaves with respect to exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With