From fa90697197d7144a4f5c9a5bd9fdacfe1819ac06 Mon Sep 17 00:00:00 2001 From: DOHA Date: Tue, 4 Nov 2014 21:29:11 +0200 Subject: [PATCH] Add Class MockitoSpyTest --- .../org/baeldung/mockito/MockitoSpyTest.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java 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..5dc9751e35 --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java @@ -0,0 +1,79 @@ +package org.baeldung.mockito; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +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 spy = spy(list); + + spy.add("one"); + spy.add("two"); + + verify(spy).add("one"); + verify(spy).add("two"); + + assertEquals(2, spy.size()); + } + + @Spy + List spyList = new ArrayList(); + + @Test + public void whenUseSpyAnnotation_thenCorrect() { + spyList.add("one"); + spyList.add("two"); + + verify(spyList).add("one"); + verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + } + + @Test + public void whenStubASpy_thenStubbed() { + final List list = new ArrayList(); + final List spy = spy(list); + + assertEquals(0, spy.size()); + + doReturn(100).when(spy).size(); + assertEquals(100, spy.size()); + } + + @Test + public void whenCreateMock_thenCreated() { + final List mockedList = mock(List.class); + + mockedList.add("one"); + verify(mockedList).add("one"); + + assertEquals(0, mockedList.size()); + } + + @Test + public void whenCreateSpy_thenCreate() { + final List spy = spy(new ArrayList()); + + spy.add("one"); + verify(spy).add("one"); + + assertEquals(1, spy.size()); + } + +}