[Mockito] Mock List interface

时间:2022-10-29 01:21:28

In this post, we are going to see more functionalities in Mockito.

Mock a List interface:

    @Test
public void testZie_returnOnce() {
List listMock = mock(List.class);
when(listMock.size()).thenReturn(10);
assertEquals(10, listMock.size());
}

Call multi times:

    @Test
public void testZie_returnMultis() {
List listMock = mock(List.class);
when(listMock.size()).thenReturn(10).thenReturn(20);
assertEquals(10, listMock.size());
assertEquals(20, listMock.size());
}

First call, return 10, second times return 20.

Mock, List.get():

    @Test
public void testZie_returnGet() {
List listMock = mock(List.class);
when(listMock.get(0)).thenReturn("Good");
assertEquals("Good", listMock.get(0));
assertEquals(null, listMock.get(1));
}

Mockito.anyInt():

    @Test
public void testZie_returnGetAny() {
List listMock = mock(List.class);
when(listMock.get(Mockito.anyInt())).thenReturn("Good");
assertEquals("Good", listMock.get(0));
assertEquals("Good", listMock.get(1));
}