Stubbing consecutive method calls

In this post under mockito, I will explain how to stub consecutive method calls with example.

Consecutive method calls meaning sometimes we call same method multiple times. In that case we have to stub the method to return values consecutively.

Below is the complete code for your reference

Test Class

1  package package7;
3  import java.util.List;
5  import org.junit.Test;
6  import org.mockito.Mockito;
8  import static org.junit.Assert.assertEquals;
9  import static org.mockito.ArgumentMatchers.anyInt;
10 import static org.mockito.Mockito.when;
12 public class ListTest {
13  @Test
14  public void testGet() {
15      List list = Mockito.mock(List.class);
16      when(list.get(anyInt())).thenReturn(1).thenReturn(2).thenReturn(3);
18      assertEquals(1, list.get(0));
19      assertEquals(2, list.get(1));
20      assertEquals(3, list.get(2));
21  }
22 }

In the above code we call List interface “get” method thrice. So we mock the List interface (Refer line 15) and stub its “get” method by using thenReturn to return 1, 2, and 3, whenever “get” method is called consecutively (Refer to line 16).

After line 16, whenever we call “get” method three times consecutively, for first call it will return 1, for second call it will return 2 and for third call it will return 3 (Refer to line 18 to 20).

Leave a Reply