Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it against best practice to throw Exception on most JUnit tests?

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?

like image 546
Chris Knight Avatar asked Mar 22 '10 23:03

Chris Knight


People also ask

Is it a good approach to throw an exception?

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.

Should I throw exception JUnit 5?

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.

How do you decide if an exception should be thrown in a method?

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.


2 Answers

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 } 
like image 156
Ophidian Avatar answered Sep 23 '22 15:09

Ophidian


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.

like image 24
Kevin Bourrillion Avatar answered Sep 22 '22 15:09

Kevin Bourrillion