Calling callbacks with Mockito

java, mockito, testing

Solution

You want to set up an `Answer` object that does that. Have a look at the Mockito documentation, at https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#answer_stubs

You might write something like

when(mockService.doAction(any(Request.class), any(Callback.class))).thenAnswer(
    new Answer<Object>() {
        Object answer(InvocationOnMock invocation) {
            ((Callback<Response>) invocation.getArguments()[1]).reply(x);
            return null;
        }
});

(replacing `x` with whatever it ought to be, of course)

Problem

I have some code ``` service.doAction(request, Callback<Response> callback); ``` How can I using Mockito grab the callback object, and call callback.reply(x)

Original source

Related problems