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