O'Reilly logo

Mockito Cookbook by Marcin Grzejszczak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required