Mockito Chaining

Dynamic mocks are great. I believe it was Martin Fowler who first switched me onto them. What we should be testing is how an object interacts with its surroundings. Often this means setting it running and verifying that it made the right outbound calls given an input. Sometimes, with more autonomous code, you need to simulate how the outside world will appear to it, and this can get complex.

Mockito is the tool of choice these days for a lot of Java developers as it has a fairly self explanatory syntax and is powerful enough for doing most of what you need. Note: Mockito is not a panacea. It can be more complex to try to pre-record in a dynamic mock what’s expected of it, than it might be to implement a simple-in-memory service that will act the way you want your simulation of a real service to act. Maybe that’s worth an article of its own another day.

I want to show how more than one Mockito doReturn, doThrow, thenReturn, thenThrow can be chained, so you can simulate something.

Let’s imagine a bit of code that’s going to use a getNext method.

public interface Source {
    String getNext();
}

Now let’s imagine a simple test set up for simulating what that would do

    Source mockSource = mock(Source.class);

    when(mockSource.getNext()).thenReturn("hello");

In the above, every time the getNext is called, it will return “hello”. Very easy. This syntax is nicest when the method returns something. The key thing is you can chain then. Let’s simulate a getNext which returns different values including throwing an exception.

    when(mockSource.getNext())
      .thenReturn("hello")
      .thenReturn("goodbye")
      .thenThrow(new RuntimeException("I ran out of data"));

The calls to that mock will get different responses each time.

This works with the doThrow/doAnswer/doReturn family of stub set ups too. These are best when your function doesn’t return something. You can use them always, but I prefer the thenReturn/thenThrow family for clarity.

Let’s imagine a void function “doSomething” and see how to mock it:

    doThrow(new RuntimeException("blah"))
        .doNothing()
        .when(mockService).doSomething();

In the above, the first call to doSomething causes an exception and the next one doesn’t.

I found this useful in practice.

Once your test has run, you may then use Mockito’s verify to see which calls were made to which mocks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s