Mockito 3 Real Partial Mocks

Mockito produces mock object, it will always call stub methods or else will use Nice Mock feature and return null. Spy will always call actual method. What if we for certain test we want to call stub method and for certain scnerio we want to call actual method.

Real Partial Mocks is to leverage the benifit of both the Mock and Spy feature.

Mockito provides thenCallRealMethod method while stubbing, it make sure that original method will be called.

package com.example.mokito3.sujan;

public class AppleService {
    public String saveApple(String apple) {
        String appleString = "i love " + apple + " apple";
        System.out.println("AppleService.saveApple:- appleString = " + appleString);
        return appleString;
    }

    public String getApple(String apple) {
        String appleString = "i eat " + apple + " apple";
        System.out.println("AppleService.getApple:- appleString = " + appleString);
        return appleString;
    }
}
package com.example.mokito3.sujan;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

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

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Captor
    ArgumentCaptor<String> argumentCaptor;
    @Mock
    private AppleService appleService;

    @Test
    void saveApplePartialMethodMockTest() {
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        when(appleService.getApple("Macintosh")).thenCallRealMethod();
        appleService.saveApple("Macintosh");
        appleService.getApple("Macintosh");
        verify(appleService).saveApple("Macintosh");
        verify(appleService).getApple("Macintosh");
    }

    @Test
    void saveApplePartialAnnotationMockTest() {
        AppleService appleService = mock(AppleService.class);
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        when(appleService.getApple("Macintosh")).thenCallRealMethod();
        appleService.saveApple("Macintosh");
        appleService.getApple("Macintosh");
        verify(appleService).saveApple("Macintosh");
        verify(appleService).getApple("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