In mockito, I want to mock a method that returns some value and also has to invoke a callback
For example, here is the service method:
String fetchString(Callback<String> callback);
I want the return value to happen before the callback is invoked. I looked into using Mockito.doAnswer(..)
but can't seem to figure out how to make the method invoke the callback after the return statement. Example:
when(mockService.fetchString(any(Callback.class)).thenAnswer(
new Answer<String>() {
String answer(InvocationOnMock invocation) {
((Callback<String>) invocation.getArguments()[0]).onResult("callback string");
return "return string";
}
});
As you can see in the example above: the callback is invoked before the value is returned. This does't test asynchronous callbacks properly. Is there a way to make the callback method be called after the value is returned?
I know that argumentCaptor can be used here, but is there an alternative that doesn't involve manually calling the callback?
Something that is a combination of doAnswer(..)
and thenReturn(..)
?