-
Notifications
You must be signed in to change notification settings - Fork 3
ExceptionCatcher
ExceptionCatcher is a utility class that makes any exception testing (hopefully) easier and cleaner.
ExceptionCatcher.tryToCatch(exceptionType,exceptionalOperation);parameters:
-
exceptionTypeis a Class object of any exception (Class<? extends Exception>), -
exceptionalOperationis an object implementing interface withoperate()method so you can pass an operation that throws exception.
returns:
- the caught exception or
nullif the specified exception was not thrown.
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);
}
});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.