Question

Verify a Method Was Not Called with Mockito in Java

javaunit-testingjunitmockitotdd

Question

How can you verify with Mockito that a specific method on a dependency was not called after testing a method?

For example, given this dependency and class:

public interface Dependency {
    void someMethod();
}

public class Foo {
    public void bar(Dependency dependency) {
        // implementation
    }
}

How should a test verify that someMethod() was never invoked on dependency after calling foo.bar(dependency)?

@Test
void dependencyIsNotCalled() {
    Foo foo = new Foo();
    Dependency dependency = mock(Dependency.class);

    foo.bar(dependency);

    // Verify here that dependency.someMethod() was not called.
}

Short Answer

Mockito can verify both actions that happened and actions that must not happen. To confirm a particular method was never called, use verify(mock, never()).method(). You can also use times(0), while verifyNoInteractions(mock) is appropriate only when the entire mock must remain unused.

Concept

A mock is a test double that records how production code interacts with it. Mockito's verify API reads that recorded interaction history after the code under test runs.

To assert that one method was not called, write:

verify(dependency, never()).someMethod();

never() means the expected invocation count is zero. If Foo.bar() calls dependency.someMethod() even once, Mockito fails the test.

This matters when an operation has an unwanted side effect. For example, an invalid request should not send an email, a cache hit should not call a remote API, and a disabled feature should not write to a database.

A negative verification should test a meaningful behavior rule, not merely mirror implementation details. It is especially useful when calling the dependency would be expensive, unsafe, or externally visible.

Mental Model

Think of a mock as a receptionist keeping an activity log for a department.

After your code finishes, verify(dependency, never()).someMethod() asks the receptionist: “Did anyone request someMethod?” The expected answer is “No.”

This is different from asking whether the whole department was untouched. The dependency may have received other valid calls; you may only want to prohibit one specific call.

Take Quiz

Syntax and Examples

The usual syntax is:

verify(mock, never()).methodCall();

For the example:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import org.junit.jupiter.api.Test;

class FooTest {
    @Test
    void dependencyMethodIsNotCalled() {
        Foo foo = new Foo();
        Dependency dependency = mock(Dependency.class);

        foo.bar(dependency);

        verify(dependency, never()).someMethod();
    }
}

never() checks that someMethod() has zero invocations. Mockito throws a verification error if the method was called.

You may also write the equivalent form:

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(dependency, times(0)).someMethod();

never() is generally easier to read because it states the intention directly.

For methods with arguments, provide the expected argument or a matcher:

verify(emailSender, never()).send("admin@example.com");
verify(emailSender, never()).send(anyString());

The first assertion allows calls with other addresses. The second assertion prohibits any call to send, regardless of its string argument.

Step by Step Execution

Consider a validation rule: blank usernames must not be saved.

class RegistrationService {
    void register(String username, UserRepository repository) {
        if (username == null || username.isBlank()) {
            return;
        }

        repository.save(username);
    }
}

Test it with a mock:

@Test
void blankUsernameIsNotSaved() {
    UserRepository repository = mock(UserRepository.class);
    RegistrationService service = new RegistrationService();

    service.register("   ", repository);

    verify(repository, never()).save(anyString());
}

Execution trace:

  1. mock(UserRepository.class) creates a mock repository and starts with an empty interaction history.
  2. register(" ", repository) is called.
  3. isBlank() returns true, so the if body executes.
  4. return exits the method before repository.save(...) can run.
  5. Mockito checks calls matching save(anyString()).
  6. The count is zero, so never() passes.

If the guard clause were removed and repository.save(username) ran, step 6 would fail the test.

Real World Use Cases

Negative verification is useful when a condition should prevent a side effect:

  • Input validation: Do not save invalid data to a repository.
  • Authorization: Do not call a payment provider when the user is not permitted.
  • Caching: Do not fetch data from a remote service on a cache hit.
  • Notifications: Do not send an email or push notification for a muted user.
  • Feature flags: Do not invoke a new integration while its feature flag is disabled.
  • Error paths: Do not continue to later processing after an earlier operation fails.

Example: a cache hit should avoid the slower API call.

String getProduct(String id) {
    String cached = cache.get(id);
    if (cached != null) {
        return cached;
    }
    return productApi.fetch(id);
}

@Test
void cacheHitDoesNotCallApi() {
    Cache cache = mock(Cache.class);
    ProductApi productApi = mock(ProductApi.class);
    when(cache.get("p-1")).thenReturn("Cached product");

    new ProductService(cache, productApi).getProduct("p-1");

    verify(productApi, never()).fetch(anyString());
}
Take Quiz

Real Codebase Usage

In production test suites, negative verification commonly supports control-flow rules.

Guard clauses and early returns

A guard clause often makes the “do not call” requirement explicit:

void process(Order order) {
    if (order.isCancelled()) {
        return;
    }
    paymentGateway.charge(order.total());
}
verify(paymentGateway, never()).charge(any());

Verify one forbidden operation

Use never() when other calls to the same dependency are valid:

service.handle(request);

verify(auditLog).record("request received");
verify(emailSender, never()).send(anyString());

Verify a dependency received no calls at all

Use verifyNoInteractions only when every interaction is forbidden:

service.handleInvalidRequest(request);

verifyNoInteractions(paymentGateway);

This is stricter than never() for a single method. It fails if any method on paymentGateway was called.

Error handling

Tests may ensure a later dependency is skipped after a failure:

when(parser.parse(input)).thenThrow(new IllegalArgumentException());

assertThrows(IllegalArgumentException.class, () -> service.importData(input));
verify(repository, never()).save(any());

Common Mistakes

Using verifyNoInteractions when only one method must not run

This is too strict if another interaction is expected:

// May fail because dependency.status() is a valid call.
verifyNoInteractions(dependency);

Prefer a focused assertion:

verify(dependency, never()).someMethod();

Forgetting to run the code under test

A negative verification can pass accidentally if the tested method was never called:

Dependency dependency = mock(Dependency.class);

// Missing: foo.bar(dependency)
verify(dependency, never()).someMethod();

Always exercise the behavior before verifying it. Also assert the observable result when possible.

Verifying the wrong mock instance

If Foo creates or receives a different dependency instance, verification against your local mock proves nothing about that other instance. Pass the mock into Foo through a constructor, method parameter, or dependency injection.

Mixing argument matchers and raw values incorrectly

When one argument uses a matcher, Mockito requires matchers for the other arguments too:

// Broken: mixes a matcher with a raw value.
verify(client, never()).send(anyString(), 3);

Use matchers consistently:

verify(client, never()).send(anyString(), eq(3));

Testing private internal calls directly

Mockito verifies calls made to collaborators, not private methods inside the class under test. Prefer testing public behavior and verifying externally meaningful side effects.

Overusing negative interaction assertions

A test that verifies many internal non-calls can become fragile during harmless refactoring. Verify non-calls that enforce an important rule, such as “do not charge,” “do not save,” or “do not notify.”

Comparisons

AssertionWhat it checksBest use
verify(mock).method()The method was called once.A required collaboration occurred.
verify(mock, times(3)).method()The method was called exactly three times.Count matters.
verify(mock, never()).method()This particular method was called zero times.One operation must not occur.
verify(mock, times(0)).method()The method was called zero times.Equivalent to never(), but less expressive.
verifyNoInteractions(mock)No methods on this mock were called.The complete dependency must be unused.
verifyNoMoreInteractions(mock)No unverified interactions remain.Strict interaction-focused tests; use carefully.

never() and times(0) have the same behavior. Choose never() for readability.

verifyNoInteractions(mock) is not a replacement for never(): it checks the entire mock, rather than one method.

Take Quiz

Cheat Sheet

import static org.mockito.Mockito.*;
NeedMockito assertion
A method must not be calledverify(mock, never()).method();
Same zero-call checkverify(mock, times(0)).method();
No calls to the mock at allverifyNoInteractions(mock);
Method must be called onceverify(mock).method();
Method must be called a specific number of timesverify(mock, times(n)).method();

With arguments:

verify(repository, never()).save(any());
verify(sender, never()).send("user@example.com");

Rules:

  • Call the code under test before verification.
  • Verify the same mock instance passed to the code under test.
  • never() checks only the specified method invocation pattern.
  • Use verifyNoInteractions only when all calls to that mock are forbidden.
  • If one argument uses a Mockito matcher, use matchers for every argument in that invocation.

FAQ

How do I verify a method was never called in Mockito?

Use verify(mock, never()).methodCall(). For example: verify(dependency, never()).someMethod();.

Is never() the same as times(0) in Mockito?

Yes. Both require zero matching invocations. never() is usually clearer to readers.

How do I verify no methods were called on a Mockito mock?

Use verifyNoInteractions(mock). It fails if any method on that mock was invoked.

Can I check that a method was not called with particular arguments?

Yes. Use concrete values or matchers in the verification:

verify(sender, never()).send("blocked@example.com");

This permits calls with different arguments. Use anyString() to prohibit all calls matching any string.

Why does verify(mock, never()) pass when my test is wrong?

It may pass because the code under test did not run, a different mock instance was used, or the verification arguments did not match the actual invocation. Exercise the method and verify the injected mock.

Should every Mockito test use verifyNoMoreInteractions?

No. It can make tests brittle because adding harmless implementation interactions breaks them. Use it only when a strictly limited interaction contract is genuinely important.

Take Quiz

Mini Project

Description

Build a small registration service that rejects blank usernames. The service must avoid writing invalid usernames to its repository, and the test will verify that this side effect does not occur.

Goal

Write a Mockito test proving that a blank username is never saved.

Requirements

  • Create a UserRepository interface with a save method.
  • Create a RegistrationService with a register method.
  • Return without saving when the username is null or blank.
  • Write a JUnit test using a Mockito mock repository.
  • Verify that save is never called for blank input.
Take Quiz

Keep learning

Related questions

View more