Mockito 除了常用的 stub 和 verify 功能外,还可以完成一些特别的 stub 操作以及使用 spy 进行特别的 mock。
Stub 返回不同值
@Mock
private List mockedList;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
@Test
public void stubMultipleResult() {
when(mockedList.get(anyInt())).thenReturn("first get").thenReturn("more than once get");
System.out.println(mockedList.get(0));
System.out.println(mockedList.get(0));
System.out.println(mockedList.get(0));
}
可以通过上面的方式使第一次调用的时候返回第一个 thenReturn 的值