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:

@InjectMocks
private PersonService personService;

@Mock
private PersonRepository personRepository;

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

@Before
public void setUp() {
    Mockito.when(personRepository.update(Mockito.any(Person.class))).thenReturn(defaultPerson);
}

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

    Assertions.assertThat(actual).isEqualTo(defaultPerson);
}

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:

@Test
public void shouldOverrideDefaultPerson() {
    Person expectedPerson = new Person("override");
    Mockito.when(personRepository.update(Mockito.any(Person.class))).thenReturn(expectedPerson);

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

    Assertions.assertThat(actualPerson).isEqualTo(expectedPerson);
}

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.