java Mockito doAnswer & thenReturn 以一种方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40420462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito doAnswer & thenReturn in one method
提问by Aplesh Rana
I have a situation where my method is returning some object, and method is containing some arguments and I have condition on the basis of returned response and one of the argument.
我有一种情况,我的方法正在返回某个对象,并且方法包含一些参数,并且我有基于返回的响应和参数之一的条件。
Map<String,List<Object>> testMap = new HashMap<>();
Object obj = new Object();
Set<String> test = myService.getModelSearchStrings(testMap, obj);
if(CollectionUtils.isNotEmpty(test){
}
if(MapUtils.isNotEmpty(testMap){
}
Test:
测试:
Set<String> result = new HashSet<>();
result.add("123");
Mockito.when(mockedMtnService.getModelSearchStrings(Mockito.anyMap(), Mockito.anyObject())).thenReturn(result);
I want to return Dummy response i.e. result HashSet and want to update argument value(Map).
我想返回虚拟响应,即结果 HashSet 并想更新参数值(映射)。
回答by LazerBass
I can only assume that you are looking for thenAnswer
& Answer. With thenAnswer
you can modify the arguments of the mocked method and also return a result from that method.
我只能假设您正在寻找thenAnswer
& Answer。随着thenAnswer
您可以修改嘲笑方法的参数,并从该方法返回一个结果。
E.g:
例如:
Set<String> result = new HashSet<>();
result.add("123");
Mockito.when(mockedMtnService.getModelSearchStrings(Mockito.anyMap(), Mockito.anyObject())).thenAnswer(new Answer<Set>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Map<String,List<Object>> mapArg = (Map<String,List<Object>>)invocation.getArguments()[0];
// do something with mapArg....
return result;
}
});
Or with Java 8 lambda:
或者使用 Java 8 lambda:
Mockito.when(mockedMtnService.getModelSearchStrings(Mockito.anyMap(), Mockito.anyObject())).thenAnswer(invocation -> {
Map<String,List<Object>> mapArg = (Map<String,List<Object>>)invocation.getArguments()[0];
// do something with mapArg....
return result;
});