0

I am coming across a Mockito.spy behavior that I cannot understand. I am spying on a method of an instance of an object and that method is returning the expected results. However the method that is being spied on is actually being called. Why is this the case? Shouldn't the method be skipped entirely and just return the thenReturn value?

This is the sample code I have explaining the behavior:

public class MockitoSample {
    public boolean methodA() {
        return methodB("a","b");
    }
    public boolean methodB(String a, String b) { //method I want to mock
        System.out.println("B called"); //why is this being called?
        return false;
    }
}

Test class, the test will pass

public class MockitoTest {
    
    @Test
    public void mockMethodB() {
        MockitoSample sampleInstance= new MockitoSample();
        MockitoSample sampleSpy = Mockito.spy(sampleInstance);
        Mockito.when(sampleSpy.methodB(Mockito.any(String.class),Mockito.any(String.class))).thenReturn(true);

        assertTrue(sampleSpy.methodA());  //passes as method B will return true now.
    }
}

Basically this line will actually call the real method and system outs "B called"

Mockito.when(sampleSpy.methodB(Mockito.any(String.class),Mockito.any(String.class))).thenReturn(true);

Why is this happening? Obviously this is a example and is passing here, but what if I have an entire implementation of methodB that I want to mock?

1 Answers1

0

stackoverflow recommended this as related and it solved my issue: Mockito: Trying to spy on method is calling the original method

Basically, using doReturn instead of when.

Mockito.doReturn(true).when(sampleSpy).methodB(Mockito.any(String.class),Mockito.any(String.class));

Also helpful response: Mockito - difference between doReturn() and when()