What is the difference between mocking and spying when using Mockito?
What would be a use case for a use of a Mockito spy?
It seems to me that every spy use case can be handled with a mock, using callRealMethod.
One difference I can see is if you want most method calls to be real, it saves some lines of code to use a mock vs. a spy. Is that it or am I missing the bigger picture?
Difference between a Spy and a Mock
When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.
In the following example – we create a mock of the ArrayList class:
@Test
public void whenCreateMock_thenCreated() {
List mockedList = Mockito.mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
}
As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:
@Test
public void whenCreateSpy_thenCreate() {
List spyList = Mockito.spy(new ArrayList());
spyList.add("one");
Mockito.verify(spyList).add("one");
assertEquals(1, spyList.size());
}
Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.
Source: http://www.baeldung.com/mockito-spy + self notes.
The answer is in the documentation:
Real partial mocks (Since 1.8.0)
Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.
callRealMethod()
was introduced after spy()
, but spy() was left there of course, to ensure backward compatibility.
Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod()
is called. In general, I would prefer using callRealMethod()
, because it doesn't force me to use the doXxx().when()
idiom instead of the traditional when().thenXxx()