0
0
JUnittesting~10 mins

when().thenReturn() stubbing in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit with Mockito
JUnit
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);
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Create mock object of List interface using Mockito.mock()mockedList is a mock List object with no behavior defined yet-PASS
2Stub the get(0) method of mockedList to return "first element" using when().thenReturn()mockedList.get(0) is now stubbed to return "first element"-PASS
3Call mockedList.get(0) to get the stubbed valuemockedList.get(0) returns "first element" as stubbedCheck that returned value equals "first element"PASS
4Assert that the returned value is "first element" using assertEqualsAssertion compares expected "first element" with actual resultassertEquals("first element", result) passesPASS
Failure Scenario
Failing Condition: The stub was not set correctly or method called with different argument
Execution Trace Quiz - 3 Questions
Test your understanding
What does when(mockedList.get(0)).thenReturn("first element") do?
AIt calls the real get(0) method on the list
BIt tells the mock to return "first element" when get(0) is called
CIt verifies that get(0) was called
DIt throws an exception when get(0) is called
Key Result
Use when().thenReturn() to define exact return values for mock methods. This helps isolate tests by controlling dependencies' behavior.