Victor Grazi Victor Grazi - 1 year ago 33
Java Question

Is it possible to call a method twice, first call the real implementation, then mock the results?

I am trying to test that a recursive method properly re-curses.
The first call should therefore

callRealMethod
. But the second call is just to verify that it was called, and should not actually make the call but rather it should return a stubbed result.

Is there any way to do this in Mockito?

Answer Source

You can simply use thenCallRealMethod, followed by a regular thenReturn stub:

import org.junit.Test;

import static org.mockito.Mockito.*;

public class PartialMock {
    String doIt() {
        return "original";
    }

    @Test
    public void testDoIt() {
        PartialMock t = mock(PartialMock.class);
        when(t.doIt())
                .thenCallRealMethod()
                .thenReturn("mocked");

        assertEquals("original", t.doIt());
        assertEquals("mocked", t.doIt());
        assertEquals("mocked", t.doIt());
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download