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 |