import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
class CalculatorService {
private final Calculator calculator;
public CalculatorService(Calculator calculator) {
this.calculator = calculator;
}
public int performAddition(int a, int b) {
return calculator.add(a, b);
}
}
public class CalculatorServiceTest {
private Calculator calculatorMock;
private CalculatorService calculatorService;
@BeforeEach
void setup() {
calculatorMock = mock(Calculator.class);
calculatorService = new CalculatorService(calculatorMock);
}
@Test
void testAddMethodCallVerification() {
// Call performAddition three times with (2,3)
calculatorService.performAddition(2, 3);
calculatorService.performAddition(2, 3);
calculatorService.performAddition(2, 3);
// Verify add called exactly 3 times with (2,3)
verify(calculatorMock, times(3)).add(2, 3);
// Verify add never called with (5,5)
verify(calculatorMock, never()).add(5, 5);
// Verify add called at least 2 times with (2,3)
verify(calculatorMock, atLeast(2)).add(2, 3);
}
}The code starts by creating a mock of the Calculator class using mock(Calculator.class). This mock is injected into the CalculatorService.
We call performAddition(2, 3) three times, which internally calls the mocked add method.
Then, we verify three things using Mockito's verify method with different times:
- times(3): Ensures
add(2, 3) was called exactly three times. - never(): Ensures
add(5, 5) was never called. - atLeast(2): Ensures
add(2, 3) was called at least two times.
This test confirms the method call counts precisely as required.