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.