Mockito Iterator Style Stubbing of Consecutive Calls

Filed Under: Mockito

Sometimes we want to mock different responses for the consecutive calls on the same method. We can create then* methods chain with when() to specify iterator style stubbing in Mockito.

Mockito Stubbing Consecutive Calls

Let’s look at a simple example of mocking exception and return a response when a method is called with same parameters. We will use JUnit 5 assertions to verify the stubbed methods.


UpdateUtils mockUU = mock(UpdateUtils.class);
		
when(mockUU.update("Data"))
	.thenThrow(new RuntimeException())
	.thenReturn("DATA");
	
assertThrows(RuntimeException.class, () -> mockUU.update("Data"));
assertEquals("DATA", mockUU.update("Data"));

//further calls will return the last mocked output
assertEquals("DATA", mockUU.update("Data"));

Notice that once the mocking chain reaches the end, further calls will return the last mocked response.

We can also provide different responses in the thenReturn() method through varargs.


when(mockUU.update("Emp")).thenReturn("EMP", "EMPLOYEE", "EMP1");

assertEquals("EMP", mockUU.update("Emp"));
assertEquals("EMPLOYEE", mockUU.update("Emp"));
assertEquals("EMP1", mockUU.update("Emp"));
assertEquals("EMP1", mockUU.update("Emp"));

This is useful in the cases where we want to mock different response in multiple executions of the same method. Note that if we define multiple methods stubbing with same arguments, then the last one will override the earlier ones.

Mockito Iterator Methods Stubbing

We can use this approach to stub an Iterator. Let’s have a look at a simple example of stubbing iterator methods through consecutive calls.


Iterator<Integer> mockIter = mock(Iterator.class);
when(mockIter.hasNext()).thenReturn(true, true, true, false);
int[] values = new int[] {1,2,3,4};
when(mockIter.next()).thenReturn(values[0], values[1], values[2], values[3]);

int index = 0;
while(mockIter.hasNext()) {
	assertTrue(values[index] == mockIter.next());
	index++;
}
You can check out complete code and more Mockito examples from our GitHub Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages