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

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!