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.

public class PersonService {

    private final PersonRepository personRepository;

    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;

    public Person update(Person person) {
        return personRepository.update(person);
public class PersonRepository {

    public Person update(Person person) {
        return person;

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:

private PersonService personService;

private PersonRepository personRepository;

private Person defaultPerson = new Person("default");

public void setUp() {

public void shouldReturnDefaultPerson() {
    Person actual = personService.update(new Person("test"));


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:

public void shouldOverrideDefaultPerson() {
    Person expectedPerson = new Person("override");

    Person actualPerson = personService.update(new Person("test"));


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.