1. Overview

In this tutorial, we’re going to look at how we can override expectations on a mock object. Mockito allows us to define expectations on our mocks. However, there are also cases where we need to reconfigure mock objects on different test methods.

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 includes 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 when().thenReturn() statements.

Let’s write our first test and configure our expectation in a @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 update() method of PersonRepository, it will return defaultPerson.

Let’s create another test method and reconfigure the return value of update() method:

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

Leave a Reply

Close Menu