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.
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()).someMethod();
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:
mock(UserRepository.class)creates a mock repository and starts with an empty interaction history.register(" ", repository)is called.isBlank()returnstrue, so theifbody executes.
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());
}
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:
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:
verify(client, never()).send(anyString(), );
Comparisons
| Assertion | What it checks | Best 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. |
Cheat Sheet
import static org.mockito.Mockito.*;
| Need | Mockito assertion |
|---|---|
| A method must not be called | verify(mock, never()).method(); |
| Same zero-call check | verify(mock, times(0)).method(); |
| No calls to the mock at all | verifyNoInteractions(mock); |
| Method must be called once | verify(mock).method(); |
| Method must be called a specific number of times | verify(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.
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?
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
UserRepositoryinterface with asavemethod. - Create a
RegistrationServicewith aregistermethod. - Return without saving when the username is
nullor blank. - Write a JUnit test using a Mockito mock repository.
- Verify that
saveis never called for blank input.
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.