Test Callback Invocation using Junit5 and Mockito

In this article we will use thenAnswer method of Mockito to invoke a callback method passed to a mock. 

Let's consider following classes.

Here, ServiceToBeTested class is calling submitCallback() method of ServiceToBeMocked class and passing it a Callback object.

The value set in Callback object is latter returned by the method being tested.


public class ServiceToBeTested {

    private final ServiceToBeMocked serviceToBeMocked;

    public ServiceToBeTested(ServiceToBeMocked serviceToBeMocked) {
        this.serviceToBeMocked = serviceToBeMocked;

    public String methodToBeTested() {
        Callback callback = new Callback();

        return "Value Received after callback = " + callback.getValue();

public class ServiceToBeMocked {

    public void submitCallback(Callback callback) {
        //some logic that sets value back in callback.

 * Simple class demonstrating callback events. The implementation could be much more complex.
public class Callback {

    private String value;

    public String getValue() {
        return value;

    public void setValue(String value) {
        this.value = value;

In above scenario, thenReturn method of Mockito will be of no use. We can use thenAnswer() method in this case to achieve our test scenario.


class ServiceToBeTestedTest {

    private ServiceToBeMocked serviceToBeMocked;

    private ServiceToBeTested serviceToBeTested;

    void test_callback() {
        Mockito.doAnswer(it -> {
            Callback callback = it.getArgument(0);
            callback.setValue("Mocked Value");
            return null;

        String returnValue = serviceToBeTested.methodToBeTested();

        Assertions.assertEquals("Value Received after callback = Mocked Value", returnValue);

Full sample code can be found at our Github repository.


Post a Comment