In mocking frameworks, you can mock an object or spy on it. What\'s the difference between the two and when would/should I use one over the other?
In Mockito if you assign any object to instance variable of Mock Object then does not affect on Mock Object.
But in case of Spy, if you assign any object to instance variable of Spy Object then does affect on Spy Object because of Spy act like real-time object modification.
For a reference example are
@RunWith(MockitoJUnitRunner.class)
public class MockSpyExampleTest {
@Mock
private List mockList;
@Spy
private List spyList = new ArrayList();
@Test
public void testMockList() {
//by default, calling the methods of mock object will do nothing
mockList.add("test");
assertNull(mockList.get(0));
}
@Test
public void testSpyList() {
//spy object will call the real method when not stub
spyList.add("test");
assertEquals("test", spyList.get(0));
}
}