1. Overview
Mockito allows us to define expectations on mock objects. Additionally, we generally must reconfigure mock objects on different test methods. In this tutorial, we're going to look at how we can override expectations on a mock object.
2. Sample Application
Let's start with our sample application.
Firstly, we have PersonRepository which holds data access operations. Then we will use PersonService which declares PersonRepository as a dependency.
3. Override Expectation
Mockito provides different methods to configure expectations. For our purposes, we'll use the when().thenReturn() statements.
Let's write our first test and configure the expectations in the @Before method:
Here, when we call the update method of PersonRepository, it'll return defaultPerson.
Now, let's create another test method and redefine the return value of update:
Here, we've written another when().thenReturn() statement - besides the one in the @Before method. As a result, Mockito overrides the first expectation and returns expectedPerson when the update method is called.
4. Summary
In this tutorial, we've looked at overriding expectations on mock objects using Mockito.
Check out the source code for the examples over on Github.