0
0
JUnittesting~10 mins

Spy objects in JUnit - Test Execution Trace

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

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.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);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Create spy object of List interfaceSpy object wrapping List.class created-PASS
3Stub get(0) method to return "hello"Spy configured to return "hello" when get(0) is called-PASS
4Call get(0) on spy objectMethod get(0) invoked on spyReturn value is "hello"PASS
5Verify get(0) was called on spyMockito verifies method invocationget(0) was called exactly oncePASS
6Assert returned value equals "hello"JUnit assertion checks equalityresult equals "hello"PASS
7Test endsTest completes successfully-PASS
Failure Scenario
Failing Condition: The spy's get(0) method is not stubbed or returns a different value
Execution Trace Quiz - 3 Questions
Test your understanding
What does the spy object do in this test?
AIt wraps the real List and allows method call verification
BIt creates a completely fake List with no real behavior
CIt automatically returns null for all methods
DIt prevents any method calls on the List
Key Result
Using spy objects lets you check if methods are called and control their return values, which helps test interactions without losing real behavior.