The Price of all “Rest with Spring” course packages will increase by $50 next Friday:

>>> GET ACCESS NOW

1. Overview

This cookbook shows how to use Mockito to configure behavior in a variety of examples and use-cases.

The format of the cookbook is example focused and practical – no extraneous details and explanations necessary.

And of course, if you want to learn more about testing well with Mockito, have a look at the other Mockito articles here.

Further reading:

Mockito Verify Cookbook

Mockito Verify examples, usage and best practices.

Read more

Mockito – Using Spies

Making good use of Spies in Mockito, and how spies are different from mocks.

Read more

Mockito’s Mock Methods

This tutorial illustrates various uses of the standard static mock methods of the Mockito API.

Read more

We’re going to be mocking a simple list implementation – the same implementation we used in the previous cookbook:

public class MyList extends AbstractList<String> {

    @Override
    public String get(final int index) {
        return null;
    }
    @Override
    public int size() {
        return 1;
    }
}

2. Cookbook

configure simple return behavior for mock

MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);

boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));

configure return behavior for mock in an alternative way

MyList listMock = Mockito.mock(MyList.class);
doReturn(false).when(listMock).add(anyString());

boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));

configure mock to throw an exception on a method call

@Test(expected = IllegalStateException.class)
public void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
    MyList listMock = Mockito.mock(MyList.class);
    when(listMock.add(anyString())).thenThrow(IllegalStateException.class);

    listMock.add(randomAlphabetic(6));
}

configure the behavior of a method with void return type – to throw an exception

MyList listMock = Mockito.mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();

listMock.clear();

configure the behavior of multiple calls

MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString()))
  .thenReturn(false)
  .thenThrow(IllegalStateException.class);

listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6)); // will throw the exception

configure the behavior of a spy

MyList instance = new MyList();
MyList spy = Mockito.spy(instance);

doThrow(NullPointerException.class).when(spy).size();
spy.size(); // will throw the exception

configure method to call the real, underlying method on a mock

MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();

assertThat(listMock.size(), equalTo(1));

configure mock method call with custom Answer

MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());

String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));

3. Conclusion

This format is an experiment – I’m publishing some of my internal development cookbooks on a given topic – on Google Guava, Hamcrest and now Mockito. The goal is to have this information readily available online – and to add to it whenever I run into a new useful example.

The implementation of all these examples and code snippets can be found in my Mockito GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

The Price of all “Rest with Spring” course packages will increase by $50 next Friday:

>>> GET ACCESS NOW

Sort by:   newest | oldest | most voted
rapgod
Guest

why should “doThrow(NullPointerException.class).when(listMock).clear();” work for stubbing methods with void return type when you have clearly stated than an exception should be thrown.

The other ways I have seen people stub methods of void return type is to use thenCallRealMethod or use spy…so again why does your method work?

Eugen Paraschiv
Guest
First – let’s clarify what that usecase is for – you have a void returning method and you’d like to simulate the behaviour of your system when that method throws an exception. Calling the real method is not the goal here – you specifically want to see how things work when that method throws an exception. Now – with that in mind – you’ll need to use the `doThrow` syntax rather than the `thenThrow` simply because you have no either choice – if your method returns void and you want to simulate it throwing an exception – that’s the only… Read more »
rapgod
Guest

Hi Eugen! Thanks for the response 🙂

So can I say that your description “configure behavior for method with no return type” is wrong then? Since what the code is doing is when you have a void returning method “simulate the behaviour of your system when that method throws an exception” and not “stub interaction with a void returning method in other to verify if the system interacts with it later in the test”

Eugen Paraschiv
Guest

You’re right – it’s a bit misleading. My thinking was – we’re configuring the behavior of that method – to throw an exception in this case, but the title doesn’t make that clear enough. I just updated it – hopefully it leaves less to interpretation. Thanks for pointing that out. Cheers,
Eugen.

Brice Vandeputte
Guest
Here is a little additionnal usefull sample on how to mock a void method (for example here how to do micro sleep instead of a legacy sleep); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { try { // Object[] args = invocation.getArguments(); // System.out.println(“called with arguments: ” + Arrays.toString(args)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }).when(mockedInstance).sleep(anyLong()); src: http://stackoverflow.com/questions/2276271/how-to-make-mock-to-void-methods-with-mockito and http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#doAnswer(org.mockito.stubbing.Answer) hop this helps
Eugen Paraschiv
Guest

Hey Brice – that’s a cool example, thanks.
Note that the article does actually cover both aspects of this example – mocking the method that returns void and a custom answer – just not together.
Cheers,
Eugen.

wpDiscuz