- 驗證調用測試類自己的方法,使用spy方法
- 驗證是否正确調用其他類方法 , 使用verify
- 驗證不會調用其他類方法,使用never
- 隻真實調用該方法,不調用其他方法如 initData() 等, 使用PowerMockito.doCallRealMethod()調用真實的方法, 測試類前添加@RunWith(PowerMockRunner.class)
- 驗證方法時,需要模拟其他方法調用的傳回值,使用Mockito.when(MockObject.method(Mockito.any(Object))).thenReturn(object);
-
驗證網絡請求onSuccess回調方法,使用ArgumentCaptor
PS:驗證調用單例類的方法,需使用PowerMockito.mockStatic(Method)
-
驗證方法抛出異常
@Test(expected = Exception.class)
-
模拟調用方法時的參數比對
when(mockedList.get(anyString())).thenReturn(element);
anyString()比對任何int參數,這表示參數為任何值,均傳回 7
-
模拟方法調用次數
time調用次數: verify(mock,times(n)).method();
atLeast至少調用的次數: verify(mock,atLeast(n)).method();
atLeastOnce最少調用一次: verify(mock,atLeastOnce()).method();
atMost最多調用次數: verify(mock,atMost(n)).method();
@Test
public void should_throw_Exception_when_setText() throws Exception {
//given
Presenter presenter=spy(Presenter.class);
View view = mock(View.class);
//when
presenter.setDate();
//then
verify(view,times(2)).setDate(7);
}