Mockito 3 Stubbing with Callback

Mockito allows us to stub a method and we use verify to validate the stub. Although we can do our most of the test case with stubbing and thenReturn() or thenThrow() method but just in case if we need to execute certain code while executing stub, then we can attach a callback method. Callback with stub is a bit controversial feature hence originally was not included in Mockito. The callback method returns an Answer Interface.

package com.example.mokito3.sujan;

    public class AppleService {
        public String processApple(String appleName) {
            return "I love Apple";
        }
}
package com.example.mokito3.sujan;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;

import java.lang.reflect.Method;
import java.util.Arrays;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock
    private AppleService appleService;

    @Test
    void saveAppleWithMockTest() {
        when(appleService.processApple("Macintosh")).thenAnswer(
                (Answer) invocation -> {
                    Object[] args = invocation.getArguments();
                    Object mock = invocation.getMock();
                    Method method = invocation.getMethod();
                    return "called with arguments: " + Arrays.toString(args) + " for mock: " + mock + " in method: " + method.getName();
                });
        System.out.println(appleService.processApple("Macintosh"));
        verify(appleService).processApple("Macintosh");

    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

 

follow us on