pavel_kazlou pavel_kazlou - 1 year ago 73
Java Question

Mockito: method's return value depends on other method called

In my unit test I need to mock an interface which among different methods has


public interface MyQueue {
Item nextItem();
boolean isEmpty();
//other methods

My requirement for the mock is that
initially should return false, but after
was called
should return true. Thus I'm mocking a queue with one item.

  1. What is the simplest way to implement this kind of mock with mockito?

  2. Can I implement additional requirement: calling
    second, third time and so on will result in a specific kind of exception?

P.S. I don't want to provide the full implementation of my interface for the test, because of other methods in it, resulting in hard-to-understand and verbose code.

Answer Source

You can achieve that with thenAnswer(), a feature Mockito documentation sees as controversial:

Yet another controversial feature which was not included in Mockito originally. We recommend using simple stubbing with toReturn() or toThrow() only. Those two should be just enough to test/test-drive any clean & simple code.

Here's thenAnswer:

private boolean called = false;

when(mock.nextItem()).thenAnswer(new Answer() {
 Object answer(InvocationOnMock invocation) {   
     called = true;       
     return item;
when(mock.isEmpty()).thenAnswer(new Answer() {
 Object answer(InvocationOnMock invocation) {          
     return called;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download