I have some code
service.doAction(request, Callback<Response> callback);
How can I using Mockito grab the callback object, and call callback.reply(x)
I have some code
service.doAction(request, Callback<Response> callback);
How can I using Mockito grab the callback object, and call callback.reply(x)
If you have a method like:-
Then following way you can mock the above method easily :-
I hope this might help someone, as i had spend lot of time in figuring out this 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_stubsYou might write something like
(replacing
x
with whatever it ought to be, of course)Consider using an ArgumentCaptor, which in any case is a closer match to "grab[bing] the callback object".
While an
Answer
is a good idea when the callback needs to return immediately (read: synchronously), it also introduces the overhead of creating an anonymous inner class, and unsafely casting the elements frominvocation.getArguments()[n]
to the data type you want. It also requires you to make any assertions about the pre-callback state of the system from WITHIN the Answer, which means that your Answer may grow in size and scope.Instead, treat your callback asynchronously: Capture the Callback object passed to your service using an ArgumentCaptor. Now you can make all of your assertions at the test method level and call
reply
when you choose. This is of particular use if your service is responsible for multiple simultaneous callbacks, because you have more control over the order in which the callbacks return.