Skip to content

ExceptionCatcher

Tomasz Kuryłek edited this page Jun 30, 2013 · 4 revisions

ExceptionCatcher is a utility class that makes any exception testing (hopefully) easier and cleaner.

ExceptionCatcher.tryToCatch(exceptionType,exceptionalOperation);

parameters:

  • exceptionType is a Class object of any exception (Class<? extends Exception>),
  • exceptionalOperation is an object implementing interface with operate() method so you can pass an operation that throws exception.

returns:

  • the caught exception or null if the specified exception was not thrown.

Simple example

Let's say we have a notStoredDocument that is not stored in our database. We also have a documentLoader with load() method that will throw an DocumentNotFoundException exception when we try to obtain a document that is not stored inside our database. Using ExceptionCatcher you could write something like this:

DocumentNotFoundException caughtException = ExceptionCatcher.tryToCatch(DocumentNotFoundException.class, new ExceptionalOperation() {
      @Override
      public void operate() throws Exception {
         documentLoader.load(notStoredDocument);
      }
   });

Comparison with try...catch

Let's say we have a method that throws an exception we want to test i.e. operationThatWillThrowException() that throws an ExpectedException. Normally you would write something like this:

@Test
public void shouldThrowAnExpectedException() {
   // when
   ExpectedException caughtException = null;
   try {
      operationThatWillThrowException();
   } catch (ExpectedException e) {
     caughtException = e;
   }
   // then
   assertThat(caughtException).isNotNull();
}

There are several problems with this test. We have a rule of thumb - code inside 'when' statement should not contain more than one operation. But as you can see it does a lot. You need to initialize caughtException with null (which is easy to forget), perform the exceptional operation, catch and assign thrown exception. Because of that it's not very clear what we are doing here. Take a look at the test using ExceptionCatcher class.

@Test
public void shouldThrowAnExpectedException() {
   // when
   ExpectedException caughtException = ExceptionCatcher.tryToCatch(ExpectedException.class, new ExceptionalOperation() {
      @Override
      public void operate() throws Exception {
         operationThatWillThrowException();
      }
   });
   // then
   assertThat(caughtException).isNotNull();
}

As you can see we're trying to catch ExceptedException which operationThatWillThrowException() throws and we're verifying that caughtException is not null. Simple and clean.

Clone this wiki locally