DEV Community

Cover image for Create and use a result captor in Mockito
Ulrich VACHON
Ulrich VACHON

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;
    }

    @Override
    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!");
doAnswer(serviceResultCaptor).when(serviceSpy).sendMessage(message);
// do the call
var serviceResult = serviceResultCaptor.getResult();
assertThat(serviceResult).isNotNull();
assertThat(serviceResult.getWhatever()).isEqualTo("Whatever");
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 github.com/ulrich/mockito-result-captor-demo

Crédit photo : https://pixabay.com/fr/users/jackmac34-483877/

Top comments (0)