Chapter 6. Things You Should Know
6.4. More about Expected Exceptions
In Section 3.7 we learned about the default approach to expected exceptions testing with JUnit using the expected attribute of the @Test annotation. In this section we will be discussing this topic in greater detail and showing how certain more complex requirements with regard to exceptions testing can be met.
But first, let us remind ourselves of what we have already learned. An example of the default expected exceptions testing pattern is presented below.
Chapter 6. Things You Should Know
Listing 6.3. Expected exceptions testing pattern - a reminder
@Test(expected = ExceptionClass.class) public void shouldThrowException() { // calling SUT's method which should // throw an exception of ExceptionClass }
There is no explicit assertion anywhere within the test code regarding the expected exception. Everything is handled through the annotation of the test method.
This pattern has three main disadvantages. Firstly, it does not allow us to inspect all the properties of the exception that has been caught – neither does it allow us to examine the properties of the SUT after the exception has been thrown. Secondly, the use of annotation makes the test code diverge from the usual pattern of arrange/act/assert (or, if you happen to be an advocate of BDD, that of given/when/
then). Thirdly, the test will pass no matter which line of the test or production code thrown the excepted exception.
It is time to learn how to deal with the expected exceptions of some not-so-basic cases.
As was previously mentioned, the rules for specifying expected exceptions in tests are the same as for the catch clause of a try-catch-finally statement: explicitly name the exceptions you expect to catch, and never use general exception classes!
6.4.1. The Expected Exception Message
On some rare occasions it is important to verify whether the exception has been thrown with a proper message or not. This is rarely the case, because the exception message is usually an implementation detail and not something your clients would care about. However, the following case - shown in Listing 6.4 - illustrates the need for exception message verification. It presents a Phone class which verifies numbers passed to it.
Listing 6.4. Phone class method throwing the same exception twice
public class Phone { private String number;
public Phone() { }
public void setNumber(String number) {
if (null == number || number.isEmpty()) { throw new IllegalArgumentException(
"number can not be null or empty");
}
if (number.startsWith("+")) {
throw new IllegalArgumentException(
"plus sign prefix not allowed, number: [" + number + "]");
}
Chapter 6. Things You Should Know
The throwing of two exceptions of the same kind could be regarded as being an instance of
"code smell"8. It would probably be better if two different exceptions were thrown.
Now imagine a test method that verifies the expected exception thrown by the setNumber() method of the Phone class. Relying solely on the exception type (in this case IllegalArgumentException) will not suffice this time.
The first thing we might do is revert to an old method of exception testing - one which uses a try- catch statement.
Listing 6.5. setNumber() method test with try/catch
Phone phone = new Phone();
@Test
public void shouldThrowIAEForEmptyNumber() { try {
phone.setNumber(null);
fail("Should have thrown IllegalArgumentException");
} catch(IllegalArgumentException iae) {
assertEquals("number can not be null or empty", iae.getMessage());
} }
@Test
public void shouldThrowIAEForPlusPrefixedNumber() { try {
phone.setNumber("+123");
fail("Should have thrown IllegalArgumentException");
} catch(IllegalArgumentException iae) {
assertEquals("plus sign prefix not allowed, " + "number: [+123]", iae.getMessage());
} }
We expect the setNumber() method to throw an exception of the InvalidArgumentException type.
If we have reached this point, then it means the expected exception has not been thrown – so it is time to fail the test (using a static fail() method of the Assert class).
Inside the catch block we can verify the exception message.
Using the try-catch statement, we can test the message of a thrown exception, or its other properties (e.g. the root cause). But we can surely all agree that it is hard to be proud of such test code. The flow of the test is obscured by the try-catch statement, the swallowed exception in the catch block is something that makes me feel uneasy every time I see it, and the use of fail() as an "inverted" assertion looks strange. If only we could get rid of this try-catch…
6.4.2. Catch-Exception Library
Listing 6.6 proves that it is possible to get rid of the try-catch statement while still being able to verify whatever we want, and to do all this adopting a nice, clean arrange/act/assert approach. It uses an additional library - Catch-Exception9 by Rod Woo, which provides some convenient methods for dealing with expected exceptions in test code.
9See http://code.google.com/p/catch-exception/
Chapter 6. Things You Should Know
Listing 6.6. Expected exceptions testing - BDD style
import static com.googlecode.catchexception.CatchException.*;
...
Phone phone = new Phone();
@Test
public void shouldThrowIAEForEmptyNumber() { catchException(phone).setNumber(null);
assertTrue(caughtException() instanceof IllegalArgumentException);
assertEquals("number can not be null or empty", caughtException().getMessage());
}
@Test
public void shouldThrowIAEForPlusPrefixedNumber() { catchException(phone).setNumber("+123");
assertTrue(caughtException() instanceof IllegalArgumentException);
assertEquals("plus sign prefix not allowed, " +
"number: [+123]", caughtException().getMessage());
}
Importing of static methods of the CatchException class from the Catch-Exception library.
The static method catchException() of the CatchException class is used to call a method which is expected to throw an exception.
The thrown exception is returned by another static method (caughtException()). The assertion verifies whether an appropriate exception has been thrown.
The exception message is likewise verified.
The code in Listing 6.6 fits nicely into arrange/act/assert. It is concise and highly readable. The static methods of the Catch-Exception library make the sequence of the code easy to grasp. Since the caught exception is available after it has been thrown (you can assign it to some variable, e.g. Exception e = caughtException()), it is possible to analyze some of its properties. In addition, if some of the methods executed within the test method are capable of throwing the same exception, a developer can specify which of them is expected to do so by wrapping specific lines of code with the catchException() method.
Thanks to this, no mistakes concerning the provenance of the caught exception are possible.
6.4.3. Testing Exceptions And Interactions
Another case where catching expected exceptions with the expected attribute of the @Test annotation is not sufficient is when there is more to be verified than just whether an appropriate exception has in fact been thrown or not. Let us consider the following example:
Chapter 6. Things You Should Know
Listing 6.7. Code to be tested for exceptions and interaction
public class RequestHandler {
private final RequestProcessor requestProcessor;
public RequestHandler(RequestProcessor requestProcessor) { this.requestProcessor = requestProcessor;
}
public void handle(Request request) throws InvalidRequestException { if (invalidRequest(request)) {
throw new InvalidRequestException();
}
requestProcessor.process(request);
}
private boolean invalidRequest(Request request) { ...
// some reasonable implementation here }
}
Method to be tested. This verifies an incoming request and throws an exception, or asks a collaborator - requestProcessor - to process it.
Now let us assume that we want to check to make sure that if an invalid request arrives, it is NOT then passed to requestProcessor, and that the appropriate exception is thrown. In such a case we will need to use a different pattern. One possibility is to follow the normal approach to exceptions handling, based on a try-catch statement. But we already know that this makes test code obscure. Let us use the Catch- Exception library once again.
Listing 6.8. Expected exceptions testing - BDD style
@Test
public void shouldThrowExceptions() throws InvalidRequestException { Request request = createInvalidRequest();
RequestProcessor requestProcessor = mock(RequestProcessor.class);
RequestHandler sut = new RequestHandler(requestProcessor);
catchException(sut).handle(request);
assertTrue("Should have thrown exception of InvalidRequestException class", caughtException() instanceof InvalidRequestException);
Mockito.verifyZeroInteractions(requestProcessor);
}
The static method catchException() of the CatchException class is used to call a method which is expected to throw an exception.
The thrown exception is returned by another static method (caughtException()). The assertion verifies whether an appropriate exception has been thrown.
We are making sure that the invalid request has not been passed to requestProcessor. We have already seen how Mockito can verify that a specific method has not been called on a mock object (with the never() method - see Section 5.4.3). Another Mockito method -
verifyZeroInteractions() - is more general in scope: it verifies whether any calls have been made to some given test doubles, and fails the test if they have.
Chapter 6. Things You Should Know
Again, the use of the Catch-Exception library makes the test code readable and allows us to verify all the properties of the tested code. This time we were interested in the right exception being thrown, and also in whether some interactions have not happened.
And What About the ExpectedException Rule?
Those of you who are familiar with the ExpectedException rule might be wondering why I haven’t discussed it. The reason is very simple: I believe it to be inferior to Catch-Exception in several respects:
• use of the ExpectedException rule breaks the arrange/act/assert or given/when/then flow, because the expectations have to be defined before the execution of exception-throwing code;
• Catch-Exception can be used with other testing libraries, which means you can use the same idiom everywhere (it is not uncommon to have projects using different technologies underway at the same company, or even with the same team involved);
• Catch-Exception allows you to specify exactly where (in which line of code) an exception is expected, whereas with the ExpectedException this is not so;
• with Catch-Exception it is possible to invoke some statements (e.g. execute some assertions or verifications) after an exception has been thrown, whereas in the case of the
ExpectedException rule the test is terminated straightaway after an exception has been thrown.
6.4.4. Conclusions
As this chapter shows, there are many ways to write test code that will verify whether an expected exception has been thrown or not. For 95% of cases the default JUnit pattern (with the expected attribute of the @Test annotation) is good enough. For the remaining few percent you can choose between using a try-catch statement and a Catch-Exception library. Of these two alternatives, the second one seems more appealing. In fact, if you want to have all your tests share the same pattern you should consider relying exclusively on the Catch-Exception library.
To complete the picture, let me also mention that matcher libraries (which are the topic of Section 6.6) offer many syntactic goodies for writing assertions relating to exceptions. For example, one can replace the following assertions:
Listing 6.9. Standard assertions
assertTrue(e instanceOf IllegalArgumentException.class);
assertEquals("number can not be null or empty", e.getMessage());
with the following one-liner:
Listing 6.10. Assertions using FEST Fluent Assertions library
Chapter 6. Things You Should Know