Java測試包Mockito
Java測試包Mockito
記錄一些基本功能,Mockito主要是用於為測試提供Mock。
生成Mock,代替目標對象
List<String> list = mock(List.class);
目標對象方法的返回結果
我們要讓mock對象的方法,按照我們的想法返回結果。使用when().then()語法定義。
when(list.get(anyInt())).then(new Answer<String>(){
@Override
public String answer(InvocationOnMock invocation)throws Throwable {
Object[] args = invocation.getArguments();
Integer num = (Integer)args[0];
if( num>3 ){
return "yes";
} else {
throw new RuntimeException();
}
}
});
當使用list.get方法時,如果參數是>3的,則返回yes
也可以使用如下語法:doAnswer().when()
doAnswer(new Answer<String>(){
@Override
public String answer(InvocationOnMock invocation)throws Throwable {
Object[] args = invocation.getArguments();
Integer num = (Integer)args[0];
if( num>3 ){
return "yes";
} else {
throw new RuntimeException();
}
}).when(list).get(anyInt());
驗證調用次數和順序
list.get(1);
list.get(4);
//是否先調用了一次list.get(1)
verify(list).get(1)
//是否調用了2次list.get()
verify(list,times(2)).get(anyInt())
Refenrece
最後更新:2017-04-03 05:39:04