Mockito的高級用法
之前寫了一篇關于《用Mockito繞過DAO層直接去測試Service層》,不太全面,這次對之前的做了點補充有的時候這個方法的返回值是通過參數(shù)返回的。比如類似于這樣:
public void test(Map map){
//do something
map.put("response","success");
}
這個時候需要這樣使用://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;
}
} ) );
@Override
public Void answer( InvocationOnMock invocation )
throws Throwable {
Object[] args = invocation.getArguments();
Map arg1 = (Map)args[0];
arg1.put("response", "failed");
return null;
}
} ) );
還有一種用法,返回參數(shù)值做為函數(shù)返回值
mockito 1.9.5之后,提供一個方便的方法來實現(xiàn)這個需要,在這之前可以使用一個匿名函數(shù)來返回一個answer來實現(xiàn)。
when(myMock.myFunction(anyString())).then(returnsFirstArg());
在這個類中還有其他的一些類似方法
returnsSecondArg()
returnsLastArg()
ReturnsArgumentAt(int position)
眼鏡蛇
posted on 2016-07-18 17:18 眼鏡蛇 閱讀(822) 評論(0) 編輯 收藏 所屬分類: Java 、Mockito