Mockito When/Then Cookbook

1. Overview

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

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

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 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 exception on 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 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 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 behavior of 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(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) {
            return "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 an Eclipse based project, so it should be easy to import and run as it is.

I usually post about Dev stuff on Google+ - you can follow me there:

Get My 3 Spring eBooks
There’s no “one single way” to build an app. This is one way that I found works well.
×
Build Your Web App with Spring (and quickly prototype it to 90%)

,

  • rapgod

    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?

    • http://www.baeldung.com/ Eugen Paraschiv

      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 way to do it. The standard when(methodCall).thenThrow… won’t compile of course because of the void return. Hope that makes it clearer. Cheers,
      Eugen.

      • rapgod

        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”

        • http://www.baeldung.com/ Eugen Paraschiv

          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.