Mockito
Unit Testing
Java
Software Development
Method Verification

How to verify that a specific method was not called using Mockito?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To verify that a specific method was not called using Mockito, use verify(mock, never()).methodName(args). The never() verification mode is the most direct and readable way to assert non-invocation. Mockito also provides verifyNoInteractions() for asserting that a mock had zero interactions of any kind, and verifyNoMoreInteractions() for asserting that no unverified interactions remain. Each serves a different testing intent, and choosing the right one produces tests that clearly communicate what behavior is being asserted.

verify with never(): Assert a Specific Method Was Not Called

never() is the standard approach when you need 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. Both produce identical behavior:

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

Prefer never() because it communicates intent more clearly. "This method should never be called" reads better than "this method should be called zero times."

Verifying with Specific Arguments

You can assert that 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(): Assert 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, not just the one you specified. It is the right choice when the entire dependency should be bypassed.

You can pass multiple mocks:

java
verifyNoInteractions(mockNotifier, mockAuditLogger, mockMetricsClient);

verifyNoMoreInteractions(): Assert No Unverified Calls

Use 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 the verifyNoMoreInteractions() call, you would not catch unexpected side effects like an extra database write or an unintended audit log call.

Comparison of Verification Methods

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

Practical Examples

Testing 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}

Testing 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}

Testing with Argument Captors

Sometimes you need to verify a method was not called while also verifying what it was called with in other scenarios:

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}

Using with @MockBean in Spring Boot Tests

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

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

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}

Common Pitfalls

  • Using verifyNoMoreInteractions as a default in every test. This makes tests brittle. If the implementation adds a harmless toString() or logging call, every test breaks. Reserve verifyNoMoreInteractions() for tests where unexpected interactions are genuinely concerning.
  • Verifying non-interaction on a real object instead of a mock. Mockito verification only works on mock objects. Calling verify() on a real instance throws NotAMockException. Ensure the object under verification was created with mock() or @Mock.
  • Forgetting argument matchers when using never(). verify(mock, never()).method("specific") only checks that the method was never called with that exact argument. It does not catch calls with different arguments. 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 produces tests that either over-constrain or under-constrain behavior.
  • Not resetting mocks between tests. In test classes with shared mock instances, interactions from one test method leak 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 the test is verifying implementation details rather than behavior. Focus on the one or two non-interactions that represent actual business rules.

Summary

  • Use verify(mock, never()).method() to assert a specific method was not called. This is the most common and readable approach.
  • Use verifyNoInteractions(mock) when the entire mock should have been completely unused.
  • Use verifyNoMoreInteractions(mock) after verifying expected calls to catch unintended side effects.
  • Prefer never() over times(0) for readability.
  • Combine with argument matchers (any(), eq()) to control how broadly the non-interaction assertion applies.
  • Avoid overusing verifyNoMoreInteractions() as a blanket assertion, as it creates brittle tests that break on harmless implementation changes.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.