Stubbing a Spy
Create a new test method to demonstrate how to stub a spy. Use the Mockito.spy()
method to create a spy object for an ArrayList. Add an element to the spy object and verify the normal behavior of the contains()
method. Then, write a stub to override the default behavior of the contains()
method to always return false for the value 5, and verify the stubbed behavior.
@Test
public void testStubbingSpy() {
ArrayList<Integer> spyArrList = Mockito.spy(new ArrayList<>());
spyArrList.add(5);
Mockito.verify(spyArrList).add(5);
assertEquals(true, spyArrList.contains(5));//Default normal behavior
Mockito.doReturn(false).when(spyArrList).contains(5);
assertEquals(false, spyArrList.contains(5));//Stubbed Behavior
}
Run the code with the following command in the terminal:
javac MockitoSpyDemo.java && java MockitoSpyDemo