DEV Community

Cover image for Create and use a result captor in Mockito

Posted on • Updated on

Create and use a result captor in Mockito

Today I will show you how to create a Mockito captor

In Mockito it exists the possibilty to use ArgumentCaptor to allow developers to verify the arguments used during the call of mocked method, but not the result itself.
Indeed, in the current release of Mockito it's not possible to capture it and my solution to do that is to build a ResultCaptor class which implements the Answer interface and generify it for more conveniance.

Let's take a look.

Create the ResultCaptor class

public static class ResultCaptor<T> implements Answer<T> {
    private T result = null;

    public T getResult() {
        return result;

    public T answer(InvocationOnMock invocationOnMock) throws Throwable {
        //noinspection unchecked
        result = (T) invocationOnMock.callRealMethod();
        return result;
Enter fullscreen mode Exit fullscreen mode

In this quite simple implementation we see that the ResultCaptor class implements the Answer interface which force to override the answer method. We use this "interceptor" to call the real method of spied bean and capture the result to store it in the current context.

Use the ResultCaptor class

ResultCaptor<ServiceResult> serviceResultCaptor = new ResultCaptor<>();
var message = new Message("id", "hello all!");
// do the call
var serviceResult = serviceResultCaptor.getResult();
Enter fullscreen mode Exit fullscreen mode

And that's it !

Let me try it

If you want a Spring boot example you can clone the repository

Crédit photo :

Top comments (0)