0
0
JUnittesting~10 mins

@Spy for partial mocking in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how to use @Spy in JUnit with Mockito to partially mock an object. It verifies that a real method is called unless it is stubbed.

Test Code - JUnit 5 with Mockito
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class SpyPartialMockTest {

    static class Calculator {
        public int add(int a, int b) {
            return a + b;
        }

        public int multiply(int a, int b) {
            return a * b;
        }
    }

    @Spy
    Calculator calculatorSpy;

    @Test
    void testPartialMockingWithSpy() {
        // Stub multiply method to return fixed value
        doReturn(10).when(calculatorSpy).multiply(2, 3);

        // Call add method - real method should be called
        int sum = calculatorSpy.add(2, 3);

        // Call multiply method - stubbed method should be called
        int product = calculatorSpy.multiply(2, 3);

        assertEquals(5, sum, "add method should call real implementation");
        assertEquals(10, product, "multiply method should return stubbed value");
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized with MockitoExtension-PASS
2Mockito creates a spy instance of CalculatorCalculator spy object ready with real methods available-PASS
3Stub multiply(2, 3) method to return 10multiply method on spy is stubbed for inputs (2,3)-PASS
4Call add(2, 3) on spyReal add method executes and returns 5Verify add returns 5PASS
5Call multiply(2, 3) on spyStubbed multiply method returns 10Verify multiply returns 10PASS
6Assertions check add == 5 and multiply == 10Assertions pass successfullyassertEquals(5, sum) and assertEquals(10, product)PASS
7Test endsTest completed with all assertions passing-PASS
Failure Scenario
Failing Condition: If the spy is not created properly or multiply method is not stubbed correctly
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @Spy annotation do in this test?
ACreates a full mock with no real method calls
BCreates a partial mock that calls real methods unless stubbed
CInjects dependencies automatically
DRuns the test in a separate thread
Key Result
Using @Spy allows you to test real method behavior while selectively overriding specific methods, which helps in testing complex objects without fully mocking them.