Test Overview
This test uses a spy object to verify that a method is called with the correct argument and that the method returns the expected value.
This test uses a spy object to verify that a method is called with the correct argument and that the method returns the expected value.
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class SpyTest { @Test public void testSpyOnList() { List<String> list = spy(new ArrayList<>()); doReturn("hello").when(list).get(0); String result = list.get(0); verify(list).get(0); assertEquals("hello", result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | — | PASS |
| 2 | Create spy object of List interface | Spy object wrapping List.class created | — | PASS |
| 3 | Stub get(0) method to return "hello" | Spy configured to return "hello" when get(0) is called | — | PASS |
| 4 | Call get(0) on spy object | Method get(0) invoked on spy | Return value is "hello" | PASS |
| 5 | Verify get(0) was called on spy | Mockito verifies method invocation | get(0) was called exactly once | PASS |
| 6 | Assert returned value equals "hello" | JUnit assertion checks equality | result equals "hello" | PASS |
| 7 | Test ends | Test completes successfully | — | PASS |
spy object in JUnit testing?Mockito.spy(realObject).Mockito.spy(new MyClass()) to create a spy.List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
spyList.add("apple");
spyList.add("banana");
Mockito.verify(spyList).add("apple");
System.out.println(spyList.size());add("apple") and add("banana") add elements to the list.add("apple") was called. The list now contains two elements, so size() returns 2.List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
Mockito.when(spyList.size()).thenReturn(5);
spyList.add("orange");
System.out.println(spyList.size());Mockito.when() can cause real method calls and errors.doReturn(5).when(spyList).size() to stub spy methods safely.save() method. You want to keep the real repository behavior but verify save() was called exactly once. Which is the best approach using spy objects?save() without changing behavior.save() was called once.save() was called once -> Option APass the test and this pattern moves unknown