diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java new file mode 100644 index 0000000000..9200a95b69 --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java @@ -0,0 +1,76 @@ +package org.baeldung.mockito; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoSpyTest { + + @Test + public void whenSpyOnList_thenCorrect() { + final List list = new ArrayList(); + final List spyList = Mockito.spy(list); + + spyList.add("one"); + spyList.add("two"); + + Mockito.verify(spyList).add("one"); + Mockito.verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + } + + @Spy + List aSpyList = new ArrayList(); + + @Test + public void whenUseSpyAnnotation_thenCorrect() { + aSpyList.add("one"); + aSpyList.add("two"); + + Mockito.verify(aSpyList).add("one"); + Mockito.verify(aSpyList).add("two"); + + assertEquals(2, aSpyList.size()); + } + + @Test + public void whenStubASpy_thenStubbed() { + final List list = new ArrayList(); + final List spyList = Mockito.spy(list); + + assertEquals(0, spyList.size()); + + Mockito.doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } + + @Test + public void whenCreateMock_thenCreated() { + final List mockedList = Mockito.mock(List.class); + + mockedList.add("one"); + Mockito.verify(mockedList).add("one"); + + assertEquals(0, mockedList.size()); + } + + @Test + public void whenCreateSpy_thenCreate() { + final List spyList = Mockito.spy(new ArrayList()); + + spyList.add("one"); + Mockito.verify(spyList).add("one"); + + assertEquals(1, spyList.size()); + } + +}