Stubbing methods so that they throw exceptions
In this recipe, we will stub a method that returns a value so that it throws an exception of our choice. This way, you can simulate scenarios in which some connection issues might occur or some business exceptions have been thrown in your application.
In the behavior verification part of our test, we will check the thrown exception and since our goal is to write beautiful tests, we will use the catch-exception library (https://code.google.com/p/catch-exception/) to assert the caught exceptions. (We will use this library even though it's not maintained any more since in JDK 8, you can profit from the lambda expressions to achieve a similar goal.)
Getting ready
First, we have to add catch-exception
to the classpath. To do that, let's use either Maven or Gradle (for manual installation, you can download the JAR files from https://code.google.com/p/catch-exception/downloads/list).
The following is the configuration for Gradle:
testCompile...