DEV Community

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

Posted on • Edited on

6 4

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/

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more