Test Overview
This test verifies how many times a mock method is called using JUnit with Mockito. It checks that a method is called exactly twice, never called with a certain argument, and called at least once.
This test verifies how many times a mock method is called using JUnit with Mockito. It checks that a method is called exactly twice, never called with a certain argument, and called at least once.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; public class VerificationTimesTest { interface Service { void performAction(String input); } @Test void testVerificationTimes() { Service mockService = mock(Service.class); // Call performAction twice with "hello" mockService.performAction("hello"); mockService.performAction("hello"); // Call performAction once with "world" mockService.performAction("world"); // Verify performAction called exactly twice with "hello" verify(mockService, times(2)).performAction("hello"); // Verify performAction never called with "test" verify(mockService, never()).performAction("test"); // Verify performAction called at least once with "world" verify(mockService, atLeast(1)).performAction("world"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized, Mockito mock created for Service interface | - | PASS |
| 2 | Calls mockService.performAction("hello") twice | Mock records two calls with argument "hello" | - | PASS |
| 3 | Calls mockService.performAction("world") once | Mock records one call with argument "world" | - | PASS |
| 4 | Verifies performAction called exactly twice with "hello" using verify(mockService, times(2)) | Mockito checks recorded calls for "hello" argument | Exactly 2 calls with "hello" found | PASS |
| 5 | Verifies performAction never called with "test" using verify(mockService, never()) | Mockito checks recorded calls for "test" argument | No calls with "test" found | PASS |
| 6 | Verifies performAction called at least once with "world" using verify(mockService, atLeast(1)) | Mockito checks recorded calls for "world" argument | At least 1 call with "world" found | PASS |
| 7 | Test ends successfully | All verifications passed | - | PASS |