mockito Mocking consecutive calls to a void return method Faking a transient error


Example

Imagine you're testing code that makes a call to this interface, and you want to make sure your retry code is working.

public interface DataStore {
    void save(Data data) throws IOException;
}

You could do something like this:

public void saveChanges_Retries_WhenDataStoreCallFails() {
    DataStore dataStore = new DataStore();
    Data data = new Data();
    doThrow(IOException.class).doNothing().when(dataStore).save(data);

    dataStore.save(data);

    verify(dataStore, times(2)).save(data);
    verifyDataWasSaved();
}