Skip to content

To Throw or to Catch exceptions in JUnit

December 12, 2009

What would happen if an exception is thrown from the test method? Obviously the test would fail. Getting an exception is not the workflow of the code and hence the test should fail.

public void testMethod() throws checkedException{



What if the exception is expected for a particular use case of the code. Here, getting an exception is an expected one and we don’t want the test to fail. So,we catch the exception in the try/ catch block and make the test case to win.

public void testMethod(){


assertEquals(true, someOtherMethod());

fail(“Should get an Exception”);

}catch(ExpectedException e){



The above test case can be modified for the unchecked expected exception as


public void testMethod(){



Catch the exceptions only when we want the code to throw the exceptions as per the api contract. In all other cases, throw the exceptions –  all the checked exceptions ,  in the throws clause of the test method and not catch the unchecked or runtime exceptions. Let the exceptions perk up and the JUnit framework would take care of it by making the test case a failed one.

What to do when an exception occurs in the set up / tear down methods?

Getting an exception in the setUp method makes the execution to halt with failure without calling the tearDown method and thus, giving us two problems. First, if the test case constructor uses the setUp method, then we are clueless to get the underlying exception cause. Second, if a resource is initialized in the setUp method before an exception, it becomes a leaking resource as the tearDown method would never be called.

With the exception in tearDown method, the JUnit framework hides the other uncaught exceptions from the test methods and displays the exception from the tearDown method with the test error.  Hence the exceptions from the tearDown methods are to be caught and handled properly.

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: