Débora
Débora

Reputation: 5952

Mockito Spy doesnot call the real object

public class VerifyClass {

    public VerifyClass() {
        System.out.println("Verify Class constructor called");
    }

    public int getSum(int a,int b){
        System.out.println("get sum called");
        return a+b;
    }

}

The above class's getSum() method is tested through spy(). Following is how the spy is used.

@Test
public void testSpy(){
    VerifyClass ob=new VerifyClass();
    VerifyClass spy=Mockito.spy( ob );
    Mockito.when(spy.getSum(1,2)).thenReturn(4);
    System.out.println("after when :" + spy.getSum(1,2));
    assertEquals(4, spy.getSum(1,2));
}

This assertEquals is passed. As far as I know, the spy should invoke the real Object's method. In this case, the getSum() should return 3 and console shows

Verify Class constructor called
get sum called
after when :4

Instead, it returns 4 which is assigned in thenReturn(4). Any clarification please ?

Upvotes: 1

Views: 404

Answers (1)

Tunaki
Tunaki

Reputation: 137309

Spying on objects means that the real method is getting called, unless it is stubbed. Quoting Mockito Javadoc (emphasis mine):

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Since in this case you are stubbing getSum (by doing Mockito.when(spy.getSum(1,2))), the real method is not getting called; the stub is.

As a side-note, the real getSum is actually getting called when you are writing Mockito.when(spy.getSum(1,2)), this is why your log shows get sum called. If you don't want that to happen, you can use

doReturn(4).when(spy).getSum(1, 2);

Upvotes: 4

Related Questions