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.
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.
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"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized with MockitoExtension | - | PASS |
| 2 | Mockito creates a spy instance of Calculator | Calculator spy object ready with real methods available | - | PASS |
| 3 | Stub multiply(2, 3) method to return 10 | multiply method on spy is stubbed for inputs (2,3) | - | PASS |
| 4 | Call add(2, 3) on spy | Real add method executes and returns 5 | Verify add returns 5 | PASS |
| 5 | Call multiply(2, 3) on spy | Stubbed multiply method returns 10 | Verify multiply returns 10 | PASS |
| 6 | Assertions check add == 5 and multiply == 10 | Assertions pass successfully | assertEquals(5, sum) and assertEquals(10, product) | PASS |
| 7 | Test ends | Test completed with all assertions passing | - | PASS |