Using catch-exception in JUnit Tests

I use ExpectedException a lot in my JUnit test to verify exceptions thrown. In some circumstances, you would also want to run some assertions in the tests after the exception is thrown. This is impossible with ExpectedException. In this post, I will demonstrate how to use catch-exception instead to achieve this.

Set up

Let say we have the following class we want to test:

public class MyService {

 private MyDao dao;
 public MyService(MyDao dao) {
      this.dao = dao;
 public void someMethod() {
      // Some codes here. Throw an exception for demo purpose
      if (true) {
           throw new NullPointerException("NPE!");

Note the method someMethod() will throw an NullPointerException. This simulates real codes that throws an exception when the object in certain state or when one of the methods it calls within returns with an exception.


ExpectedException works by wrapping the entire test method by its own try-catch block. As a result, any assertion statements after the method that throws the exception are not called.

public class MyTest {

 public ExpectedException none = ExpectedException.none();
 public void testUsingExpectedException() {
      MyDao mockDao = mock(MyDao.class);
      MyService service = new MyService(mockDao);
      // Note the following line is not called. Test still passes

Note the test above verifies that the NPE is thrown as expected. The dao’s afterException method is never called and the test will still pass.


Catch-exception is a library that would address the issue above with ExpectedException. To use it, include the following Maven dependency

      <scope>test</scope> <!-- test scope to use it only in tests -->

and update the test as follows

 public void testUsingCatchException() {
      MyDao mockDao = mock(MyDao.class);
      MyService service = new MyService(mockDao);
      // Hamcrest
      assertThat(caughtException(), instanceOf(NullPointerException.class));
      // Mockito verify got called
      verify(mockDao, never()).afterException();

Now the assertion (mockito verify) statements are called. This could be useful if you want to verify that the object is in the correct state or as in the example certain methods of the object’s member is (not) called when the method throws an exception.

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.