How to call real method using mock object

This post explains how to call real methods of an instance when writing junit test cases using mockito.


import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class Class1Test {
    @Mock
    private Class1 class1;

    @Test
    public void testMethod1() {
        //Stubbed the method1 of Class1 to return some random value
        when(class1.method1(anyInt())).thenReturn(2);
        System.out.println(class1.method1(3));

        //Calling the real method using the mock object
        when(class1.method1(anyInt())).thenCallRealMethod();
        System.out.println(class1.method1(3));
    }
}

class Class1 {
    public int method1(int value) {
        return value * value;
    }
}

Explanation

If we see the above code, we use ‘thenCallRealMethod’ to instruct mockito to call real method when Class1’s method1 is called.

Output

2
9

Leave a Reply