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;
2  
3  import java.util.List;
4  
5  import org.junit.Test;
6  import org.mockito.Mockito;
7  
8  import static org.junit.Assert.assertEquals;
9  import static org.mockito.ArgumentMatchers.anyInt;
10 import static org.mockito.Mockito.when;
11 
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);
17      
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).

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