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).
Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call. Use doAnswer() when you want to stub a void method with generic Answer .
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
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.
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:
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With