Test Overview
This test uses Mockito's when().thenReturn() to stub a method call. It verifies that the stubbed method returns the expected value when called.
This test uses Mockito's when().thenReturn() to stub a method call. It verifies that the stubbed method returns the expected value when called.
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import java.util.List; public class ListStubTest { @Test public void testWhenThenReturnStubbing() { // Create mock List<String> mockedList = mock(List.class); // Stub method when(mockedList.get(0)).thenReturn("first element"); // Call stubbed method String result = mockedList.get(0); // Verify returned value assertEquals("first element", result); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Create mock object of List interface using Mockito.mock() | mockedList is a mock List object with no behavior defined yet | - | PASS |
| 2 | Stub the get(0) method of mockedList to return "first element" using when().thenReturn() | mockedList.get(0) is now stubbed to return "first element" | - | PASS |
| 3 | Call mockedList.get(0) to get the stubbed value | mockedList.get(0) returns "first element" as stubbed | Check that returned value equals "first element" | PASS |
| 4 | Assert that the returned value is "first element" using assertEquals | Assertion compares expected "first element" with actual result | assertEquals("first element", result) passes | PASS |