Mockito
Unit Testing
Java
Software Development
Method Verification

Mockito: verify a method was not called (never, verifyNoInteractions)

Codemia Knowledge Hub ·

To verify that a specific method was not called using Mockito, use verify(mock, never()).methodName(args). never() is the most direct and readable way to assert non-invocation. Mockito also has verifyNoInteractions(), which asserts a mock had zero interactions of any kind, and verifyNoMoreInteractions(), which asserts no unverified interactions remain. Each expresses a different testing intent.

verify with never(): one specific method was not called

never() is the standard way to verify that one particular method was not invoked:

java
1import static org.mockito.Mockito.*;
2
3@Test
4void shouldNotDeleteUserWhenFlagIsFalse() {
5    UserRepository mockRepo = mock(UserRepository.class);
6    UserService service = new UserService(mockRepo);
7
8    service.processUser("john", false);
9
10    // Assert deleteUser was never called with any argument
11    verify(mockRepo, never()).deleteUser(anyString());
12}

never() is equivalent to times(0) but reads more naturally:

java
// These two lines are functionally identical
verify(mockRepo, never()).deleteUser(anyString());
verify(mockRepo, times(0)).deleteUser(anyString());

Prefer never(): "this method should never be called" reads better than "this method should be called zero times."

Not called with specific arguments

You can assert a method was not called with specific arguments while allowing calls with other arguments:

java
1@Test
2void shouldNotDeleteAdminUsers() {
3    UserRepository mockRepo = mock(UserRepository.class);
4    UserService service = new UserService(mockRepo);
5
6    service.cleanupInactiveUsers();
7
8    // Assert deleteUser was never called with "admin"
9    verify(mockRepo, never()).deleteUser("admin");
10
11    // But it may have been called with other usernames (this is allowed)
12}

verifyNoInteractions(): zero activity on a mock

Use verifyNoInteractions() when a mock should not have been touched at all:

java
1@Test
2void shouldSkipNotificationWhenUserOptedOut() {
3    NotificationService mockNotifier = mock(NotificationService.class);
4    UserRepository mockRepo = mock(UserRepository.class);
5    UserService service = new UserService(mockRepo, mockNotifier);
6
7    User optedOutUser = new User("jane", false);  // opted out of notifications
8    service.processUser(optedOutUser);
9
10    // Assert the notification service was completely untouched
11    verifyNoInteractions(mockNotifier);
12}

This is stronger than verify(mock, never()).someMethod() because it catches calls to any method on the mock. Use it when the entire dependency should be bypassed.

You can pass multiple mocks:

java
verifyNoInteractions(mockNotifier, mockAuditLogger, mockMetricsClient);

verifyNoMoreInteractions(): no unverified calls

Call verifyNoMoreInteractions() after verifying expected interactions to ensure nothing else happened:

java
1@Test
2void shouldOnlySaveAndNotify() {
3    UserRepository mockRepo = mock(UserRepository.class);
4    NotificationService mockNotifier = mock(NotificationService.class);
5    UserService service = new UserService(mockRepo, mockNotifier);
6
7    service.registerUser("alice");
8
9    // Verify expected interactions
10    verify(mockRepo).save(any(User.class));
11    verify(mockNotifier).sendWelcomeEmail("alice");
12
13    // Assert nothing else happened
14    verifyNoMoreInteractions(mockRepo, mockNotifier);
15}

Without it, you would miss unexpected side effects like an extra database write or an unintended audit log call.

never() vs verifyNoInteractions vs verifyNoMoreInteractions

MethodScopeUse CaseFails When
verify(mock, never()).method()Single methodSpecific method must not be calledThat specific method was called
verifyNoInteractions(mock)Entire mockMock should be completely unusedAny method was called on the mock
verifyNoMoreInteractions(mock)Unverified callsNo surprise calls beyond what was verifiedUnverified method calls exist
verify(mock, times(0)).method()Single methodSame as never() (less readable)That specific method was called

Examples

Conditional logic

java
1@Test
2void shouldNotChargeWhenBalanceIsSufficient() {
3    PaymentGateway mockGateway = mock(PaymentGateway.class);
4    BillingService billing = new BillingService(mockGateway);
5
6    Account account = new Account("acc-1", 500.00);  // balance is enough
7    billing.processOrder(account, 100.00);
8
9    // Should use account balance, not charge the payment gateway
10    verify(mockGateway, never()).charge(anyString(), anyDouble());
11}

Error paths

java
1@Test
2void shouldNotCommitOnValidationFailure() {
3    TransactionManager mockTx = mock(TransactionManager.class);
4    Validator mockValidator = mock(Validator.class);
5    OrderService service = new OrderService(mockTx, mockValidator);
6
7    when(mockValidator.validate(any())).thenReturn(false);
8
9    service.placeOrder(new Order());
10
11    verify(mockTx, never()).commit();
12    verify(mockTx, never()).beginTransaction();
13    // Alternatively, assert the entire mock was unused:
14    // verifyNoInteractions(mockTx);
15}

With argument captors

To verify a method was not called for some inputs while checking what it was called with for others:

java
1@Test
2void shouldOnlyNotifyActiveUsers() {
3    NotificationService mockNotifier = mock(NotificationService.class);
4    UserService service = new UserService(mockNotifier);
5
6    List<User> users = List.of(
7        new User("alice", true),   // active
8        new User("bob", false),    // inactive
9        new User("carol", true)    // active
10    );
11
12    service.sendBroadcast(users, "Hello!");
13
14    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
15    verify(mockNotifier, times(2)).notify(captor.capture(), eq("Hello!"));
16
17    assertThat(captor.getAllValues()).containsExactly("alice", "carol");
18    // Implicitly, bob was not notified (verified by times(2) + captured values)
19
20    // Explicit verification that bob was never notified
21    verify(mockNotifier, never()).notify(eq("bob"), anyString());
22}

With @MockBean in Spring Boot tests

In Spring Boot integration tests, verification works the same way with @MockBean:

java
1@SpringBootTest
2@AutoConfigureMockMvc
3class OrderControllerTest {
4
5    @MockBean
6    private PaymentGateway paymentGateway;
7
8    @MockBean
9    private InventoryService inventoryService;
10
11    @Autowired
12    private MockMvc mockMvc;
13
14    @Test
15    void shouldNotChargePaymentForFreeItems() throws Exception {
16        mockMvc.perform(post("/orders")
17                .contentType(MediaType.APPLICATION_JSON)
18                .content("{\"item\": \"free-sample\", \"price\": 0}"))
19                .andExpect(status().isOk());
20
21        verify(paymentGateway, never()).charge(anyString(), anyDouble());
22        verify(inventoryService).reserve(eq("free-sample"), eq(1));
23        verifyNoMoreInteractions(paymentGateway);
24    }
25}

InOrder verification with never()

When the order of interactions matters, combine InOrder with never():

java
1@Test
2void shouldValidateBeforeSavingAndNeverDeleteOnSuccess() {
3    UserRepository mockRepo = mock(UserRepository.class);
4    Validator mockValidator = mock(Validator.class);
5
6    when(mockValidator.isValid(any())).thenReturn(true);
7
8    UserService service = new UserService(mockRepo, mockValidator);
9    service.register(new User("alice"));
10
11    InOrder inOrder = inOrder(mockValidator, mockRepo);
12    inOrder.verify(mockValidator).isValid(any());
13    inOrder.verify(mockRepo).save(any());
14    inOrder.verify(mockRepo, never()).delete(any());
15}

Mistakes that make these tests brittle or wrong

  • Using verifyNoMoreInteractions as a default in every test. This makes tests brittle: if the implementation adds a harmless extra call, such as a logging call on the mock, every test breaks. Reserve verifyNoMoreInteractions() for tests where unexpected interactions genuinely matter, and avoid using it as a blanket assertion.
  • Verifying non-interaction on a real object instead of a mock. Mockito verification only works on mocks. Calling verify() on a real instance throws NotAMockException, so create the object with mock() or @Mock.
  • Forgetting argument matchers when using never(). verify(mock, never()).method("specific") only checks that exact argument and misses calls with different ones. Use anyString() or any() for broader assertions.
  • Confusing verifyNoInteractions with verifyNoMoreInteractions. verifyNoInteractions fails if any method was called at all. verifyNoMoreInteractions fails only for calls that have not been explicitly verified. Mixing them up over-constrains or under-constrains behavior.
  • Not resetting mocks between tests. With shared mock instances, interactions leak from one test method into another. Use @BeforeEach with reset(mock) or, better, create fresh mocks per test.
  • Over-mocking. Verifying that ten methods were never called usually means you are testing implementation details, not behavior. Focus on the one or two non-interactions that represent real business rules.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms