之前寫了一篇關于《
用Mockito繞過DAO層直接去測試Service層》,不太全面,這次對之前的做了點補充
有的時候這個方法的返回值是通過參數返回的。比如類似于這樣:
public void test(Map map){
//do something
map.put("response","success");
}
這個時候需要這樣使用:
when( myMock.someMethod( any( Map.class ) ) ).thenAnswer( ( new Answer<Void>() {
@Override
public Void answer( InvocationOnMock invocation )
throws Throwable {
Object[] args = invocation.getArguments();
Map arg1 = (Map)args[0];
arg1.put("response", "failed");
return null;
}
} ) );
還有一種用法,返回參數值做為函數返回值
mockito 1.9.5之后,提供一個方便的方法來實現這個需要,在這之前可以使用一個匿名函數來返回一個answer來實現。
when(myMock.myFunction(anyString())).then(returnsFirstArg());
其中returnsFirstArg()是org.mockito.AdditionalAnswers中的一個靜態方法。在這個類中還有其他的一些類似方法returnsSecondArg()returnsLastArg()
ReturnsArgumentAt(int position)
眼鏡蛇