In the Mockito mocking library, how do you assert that a method was called on a mock, and how do you assert it was called an exact number of times?
answer
- verify(mock).m() == times(1)
- verify returns mock in verification mode
- VerificationMode = count strategy
- all-or-nothing matchers per call
- counts cumulative since mock creation
basics
~20 sUse verify(mock).method(args) - it asserts exactly one matching call. For other counts pass a mode: verify(mock, times(3)).method(args). Arguments match by equals or by matchers. A mismatch throws an assertion error showing wanted versus actual invocations.
solid answer
~50 sVerification is written `verify(mock).someMethod(args)`. `verify` returns the mock in *verification mode*, so the call that follows is not a real invocation - it describes the invocation you expect. The bare form is shorthand for `verify(mock, times(1))`, exactly one matching call; for another count you pass the mode explicitly: `verify(mock, times(3)).save(order)`. Matching is per invocation and per argument: a recorded call counts only if the method and every argument match, using `equals()` by default or matchers such as `any()`, `eq()`, `argThat(...)`. If you use a matcher for one argument you must use matchers for all of them. Counts are cumulative over the mock's life - since creation, or since `clearInvocations`/`reset`. Verification is an assertion, so it belongs after the act phase, and a failure throws a `MockitoAssertionError` subclass whose message shows wanted versus actual with the stack trace of the offending call.
code
java · 21 lines@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repo;
@InjectMocks OrderService service;
@Test
void savesEachOrderOnce() {
service.place(new Order("A"));
verify(repo).save(new Order("A")); // exactly once
verify(repo, times(1)).save(any(Order.class)); // same thing, explicit
}
@Test
void retriesThreeTimes() {
service.placeWithRetry(new Order("B"));
verify(repo, times(3)).save(any(Order.class));
}
}go deeper
Know the syntax cold: verify(mock).method(args) for once, times(n) for n, and that it goes after the code under test runs.
Explain that verify puts the mock in verification mode, that the mode is a count strategy, and that matching is per argument via equals() or matchers.
Add judgement: verify side effects that have no other observable trace, avoid verifying calls whose return value is already asserted, and read the failure output rather than guessing.
Frame interaction verification as coupling to a collaborator's protocol - useful at real boundaries, corrosive when it pins internal call shapes that refactors will move.
## What verification is A *mock* is a stand-in object that records every call made to it. Working with a mock has two phases: **stubbing** ("when this is called, return that"), set up before the code under test runs, and **verification** ("this call happened, this many times"), asserted after it runs. Verification asserts about *interactions* rather than about returned state - you reach for it when the meaningful effect of the code under test is a call to a collaborator (a repository save, an email send, a metric increment) that returns nothing you can inspect. ## The syntax and why it looks like that `verify(mock)` does not itself assert anything. It puts the mock into a one-shot verification mode and returns the same proxy. The very next method call on that proxy is intercepted and treated as the *description* of the invocation you are looking for, not as a real call: ```java verify(repo).save(order); ``` This reads as "assert that `save(order)` was called on `repo` exactly once". The bare `verify(mock)` is defined as `verify(mock, times(1))`. The second argument is a `VerificationMode` - a small strategy object that receives all recorded invocations matching the description and decides whether the count is acceptable. `times(n)` demands exactly *n*. ## How invocations are matched An invocation is a candidate only if the mock, the method, and every argument match. Arguments are compared with `equals()` unless you use argument matchers (`any()`, `anyString()`, `eq(x)`, `argThat(predicate)`). Mockito's matcher mechanism works through a thread-local stack, which is why mixing raw values and matchers in one call throws `InvalidUseOfMatchersException`: once one argument is a matcher, all must be (`eq(5)` wraps a raw value). Because matching depends on `equals()`, verifying with a mutable argument object is a classic trap: if the code under test mutates the object after the call, the recorded reference now equals a different state and your verification either passes or fails for the wrong reason. Argument captors or `argThat` on immutable fields are the way out. ## Counting semantics Counts are per mock and cumulative from mock creation. A mock created fresh per test (the usual `@Mock` + `MockitoExtension` setup) starts empty each time, which is why counts stay meaningful. `clearInvocations(mock)` wipes recorded invocations but keeps stubbing; `reset(mock)` wipes both and is generally a sign the test is doing too much. Multiple `verify` calls on the same mock are independent assertions, each with its own description - they do not accumulate into a sequence, and they do not forbid other calls from happening. ## Failure output When the count is wrong, Mockito throws a `MockitoAssertionError` subclass and prints a message with the wanted invocation, the actual count, and stack traces pointing at both the verification line and the real call sites. That message is designed to be read directly; treating it as noise and guessing is the most common time sink for beginners. ## Where it fits in a test Arrange - stub what the code needs to run. Act - call the method under test. Assert - check returned values with your assertion library and check side effects with `verify`. Verifying a call you also stubbed adds nothing when the return value already flows into an assertion; verify what has no other observable trace.
- Why does Mockito throw InvalidUseOfMatchersException when you write verify(repo).find(any(String.class), 42)?Matchers are not values; each matcher call pushes an entry onto a thread-local stack that Mockito pops when it builds the invocation description. Mixing a raw value with matchers leaves the stack out of sync with the argument list, so Mockito cannot tell which argument the matcher belongs to. The fix is to wrap the raw value: `verify(repo).find(any(String.class), eq(42))`.
- You verified save(order) and it fails even though your code clearly called save. What would you check first?Argument equality. Mockito matches recorded arguments with equals(), so a value object without equals/hashCode, or an object mutated after the call, will not match. The failure message lists the actual invocation with its arguments, so compare it against what you wanted; if the difference is legitimate, switch to an ArgumentCaptor or argThat and assert on the fields you actually care about.
saying these in an interview costs you the question
- Thinking verify(mock).save(order) actually invokes save on the mock
- Believing verify(mock, times(1)) forbids other methods from being called on that mock
- Putting verify before the act phase
- Mixing raw arguments and matchers in one verified call
- Assuming argument matching uses reference identity rather than equals()