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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s