Verify spy object records method calls correctly
Preconditions (2)
✅ Expected Result: The spy object records the method call correctly, the verification passes, and the assertion confirms the result is 8
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; class Calculator { public int add(int a, int b) { return a + b; } } public class CalculatorSpyTest { @Test void testAddMethodCalledOnceWithCorrectParameters() { // Create a real Calculator instance Calculator realCalculator = new Calculator(); // Create a spy of the real Calculator Calculator spyCalculator = spy(realCalculator); // Call add method on spy int result = spyCalculator.add(5, 3); // Verify add was called once with 5 and 3 verify(spyCalculator).add(5, 3); // Assert the result is 8 assertEquals(8, result, "The add method should return 8"); } }
This test creates a spy object of the Calculator class using Mockito.spy(). The spy wraps a real Calculator instance, so the actual add method runs.
We call add(5, 3) on the spy, then use verify() to check that the method was called exactly once with those parameters.
Finally, we assert the returned result is 8 using JUnit's assertEquals(). This confirms both the spy recorded the call and the method behaves correctly.
This approach helps test interactions with real objects while still verifying method calls.
Now add data-driven testing with 3 different input pairs for the add method using JUnit 5 parameterized tests and spy objects.
spy object in JUnit testing?Mockito.spy(realObject).Mockito.spy(new MyClass()) to create a spy.List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
spyList.add("apple");
spyList.add("banana");
Mockito.verify(spyList).add("apple");
System.out.println(spyList.size());add("apple") and add("banana") add elements to the list.add("apple") was called. The list now contains two elements, so size() returns 2.List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
Mockito.when(spyList.size()).thenReturn(5);
spyList.add("orange");
System.out.println(spyList.size());Mockito.when() can cause real method calls and errors.doReturn(5).when(spyList).size() to stub spy methods safely.save() method. You want to keep the real repository behavior but verify save() was called exactly once. Which is the best approach using spy objects?save() without changing behavior.save() was called once.save() was called once -> Option APass the test and this pattern moves unknown