2 Minutes To Code (β Version)

Mockito - 2 minute tutorial

How to stub method for sequential calls

The example below shows the mock objects behaviour when its method is stubbed multiple times.

In line no. 11, the mock object myMockedList is asked to return String "target" when get(0) is called on it. Then it is asked to return String "others" on next call.

The resulting behaviour is that on first call of get(0), the string target is returned and from then onwards on all subsequent calls of get(0), the string others is returned.

Aslo, notice an alternate way of doing this as shown in line no. 12.
package com.techfundaes.mockitoBag;

import static org.mockito.Mockito.*;
import java.util.List;

public class SequentialMethodCalls
{
	public static void main(String[] args)
	{
		List myMockedList = mock(List.class); 
		when(myMockedList.get(0)).thenReturn("target").thenReturn("others");
		//when(myMockedList.get(0)).thenReturn("target", "others", "more");
		
		System.out.println(myMockedList.get(0));
		System.out.println(myMockedList.get(0));
		System.out.println(myMockedList.get(0));
	}
}