skip to content

Verification

Asserting that interactions happened: call counts, ordering across mocks, proving nothing else was touched, and waiting for async calls. Interviewers use this area to see whether you verify behavior that matters or reflexively over-verify every interaction.

on this pageshow

explore

questions

17

You need a test to prove that a mocked collaborator's open() method was called before its write() method. How do you express that ordering in Mockito, and why are two ordinary verify() calls not enough?

level: juniorimportance: must knowfreq 40%

answer

  1. InOrder inOrder = inOrder(mocks)
  2. verify through the handle, not statically
  3. cursor moves forward, never backward
  4. spans multiple mocks
  5. subsequence, gaps allowed

basics

~20 s

Create an ordering handle with InOrder inOrder = inOrder(mock), then call inOrder.verify(mock).open() followed by inOrder.verify(mock).write(...). Plain verify() only checks that each call happened at all; it ignores sequence, so it passes even if write ran first.

solid answer

~50 s

Ordinary verify(mock).open() and verify(mock).write(data) each ask a single question: did this call happen? Mockito records invocations in order, but plain verification never consults that order, so the pair passes for either sequence. For ordering you create an InOrder handle over the mocks you care about and verify through it: InOrder inOrder = inOrder(resource); inOrder.verify(resource).open(); inOrder.verify(resource).write(data); The handle keeps a cursor into the recorded invocation list. Each inOrder.verify searches forward from the cursor for a matching call and moves the cursor past it; if the match is only found before the cursor, the verification fails. It also works across several mocks: pass them all to inOrder(a, b). Two details worth saying: the handle must be verified through (a plain static verify is order-blind even while an InOrder exists), and the check is a subsequence check, not an exact-transcript check — unverified calls in between are allowed.

code

java · 9 lines
java
InOrder inOrder = inOrder(resource);
inOrder.verify(resource).open();
inOrder.verify(resource).write(data);
inOrder.verify(resource).close();

InOrder tx = inOrder(txManager, repository);
tx.verify(txManager).begin();
tx.verify(repository).save(entity);
tx.verify(txManager).commit();

go deeper

for a junior

Show the three lines (create handle, verify, verify) and state clearly that plain verify ignores order.

for a middle

Explain the forward-moving cursor, cross-mock handles, and that unverified calls in between are tolerated.

for a senior

Add failure semantics (VerificationInOrderFailure), the static-verify pitfall, and when ordering is contract versus over-specification.

for a principal

Frame ordering assertions as an interaction-contract decision: assert only orders whose violation is a real defect, to keep tests from ossifying implementation detail.

## What Mockito records and what plain verify asks Every mock keeps an ordered list of the invocations it received. A plain verify(mock).open() runs a matcher over that whole list and asserts the number of matches (once, by default). Position never enters into it. So a test with verify(resource).open(); verify(resource).write(data); passes whether the production code opened then wrote, or wrote then opened — which is exactly the bug such a test is often written to prevent. ## The InOrder handle Mockito.inOrder(Object... mocks) returns an InOrder object that carries a shared verification cursor across the mocks you pass in. Verifications performed through that handle are position-aware: InOrder inOrder = inOrder(resource); inOrder.verify(resource).open(); inOrder.verify(resource).write(data); inOrder.verify(resource).close(); Each call scans forward from the current cursor for the first invocation matching the wanted method and arguments. On success the cursor advances past that invocation, so subsequent verifications can only match later calls. If no match exists at or after the cursor — for instance because write happened before open — Mockito fails with a VerificationInOrderFailure saying the wanted invocation was not found in order (often with a 'Wanted ... but was ...' comparison). ## Rules people trip over Only verifications made through the handle are ordered. Mixing in a plain Mockito.verify(resource).write(data) adds an unordered assertion and does not move the cursor. Only mocks passed to inOrder() participate; verifying a mock that was not passed in is a misuse error, and interactions with mocks outside the handle are invisible to it. Argument matchers work exactly as in normal verification, so inOrder.verify(resource).write(argThat(...)) is fine, and a call with different arguments simply does not match. ## Ordering across collaborators The same handle spans mocks, which is how you assert cross-object protocols: InOrder inOrder = inOrder(txManager, repository); inOrder.verify(txManager).begin(); inOrder.verify(repository).save(entity); inOrder.verify(txManager).commit(); This is a genuine strength of InOrder — it verifies the interleaving of two objects, which no per-mock assertion can express. ## It is a subsequence, not a transcript InOrder asserts relative order of the calls you verify, and tolerates any other calls before, between or after them. That keeps the test from breaking when unrelated interactions are added, but it also means the test is not asserting 'these and only these calls, in this order'. To tighten it you add inOrder.verifyNoMoreInteractions() or a separate exact-count verification. ## When to reach for it Ordering assertions are valuable when the order is part of the contract: lock before mutate, begin before save before commit, validate before persist, write header before body, close after flush. They are over-specification when the order is an incidental implementation choice — asserting it then makes a harmless refactor fail. A useful habit is to write ordinary verifications by default and reach for InOrder only when you can name the bug that reordering would cause.

  • What happens if you call the static Mockito.verify() instead of inOrder.verify() while an InOrder handle exists?
    You get a normal, order-blind verification: it asserts the call happened but ignores position and does not advance the handle's cursor. The test then silently loses the ordering guarantee it appears to make, which is why every assertion that is meant to be ordered must go through the handle.
  • Can you verify order for a mock you did not pass to inOrder()?
    No. Mockito raises a misuse error telling you the mock is not part of the in-order verification. The handle only tracks the mocks it was given, and interactions with any other mock are simply invisible to it, so all participants in the protocol must be listed when the handle is created.

Plain verify is checking a guest list — did these people attend? InOrder is checking the CCTV timeline — did this one walk in before that one?

saying these in an interview costs you the question

  • Believing consecutive plain verify() calls already assert order
  • Creating an InOrder handle but then verifying statically
  • Thinking the order of verify statements affects a plain verification
  • Expecting an error when extra unverified calls happen between the verified ones
  • Assuming a separate InOrder per mock can express cross-mock ordering

context

open as a page

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?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Use 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.

open as a page

In the Mockito mocking library, how do you assert that a collaborator was not touched at all during a test, and how is that different from asserting that one particular method was not called?

level: juniorimportance: must knowfreq 52%

basics

~20 s

Use verifyNoInteractions(mock) - it fails if any method at all was called on that mock. Asserting one method was not called is verify(mock, never()).method(args), which is scoped to that method and those arguments and says nothing about the rest of the mock.

open as a page

In a Mockito test the collaborator is invoked from a background thread, so a plain verify() runs before the call happens. How does verify(mock, timeout(1000)).method() solve that, and what is Mockito doing during that second?

level: middleimportance: must knowfreq 45%

basics

~20 s

timeout(ms) wraps the verification mode in a retry loop: Mockito re-checks the mock's recorded calls about every 10 ms until the check passes or the budget expires, then rethrows the last failure. It returns the moment it succeeds, so the number is an upper bound, not a sleep.

open as a page

Mockito offers both verify(mock, timeout(200)).send(msg) and verify(mock, after(200)).send(msg). How does each one spend those 200 milliseconds, and what can one catch that the other cannot?

level: middleimportance: must knowfreq 38%

basics

~20 s

timeout(200) polls and returns as soon as the verification passes, so it is an upper bound. after(200) always waits the whole 200 ms and only then asserts, so it can catch extra or late calls that timeout would have already passed over.

open as a page

Code under test calls a mock's a(), then b(), then c(). A Mockito test creates an InOrder handle with inOrder(mock) and verifies only a() and then c() through it. Does that pass, and what exactly is such an ordered verification asserting about the sequence?

level: middleimportance: must knowfreq 32%

basics

~20 s

It passes. Mockito's InOrder asserts a subsequence: the verified calls must appear in the given relative order, but any number of unverified calls may occur before, between or after them. It never asserts that nothing else happened.

open as a page

Beyond asserting an exact call count, what verification modes does Mockito offer for expressing 'not at all', 'at least n times' and 'at most n times', and when would you prefer each?

level: middleimportance: should knowfreq 58%

basics

~20 s

never() asserts zero matching calls (same as times(0)). atLeastOnce() and atLeast(n) assert a lower bound; atMost(n) asserts an upper bound. Use bounds when the exact count is an implementation detail - retries, caching, loops - and exact times(n) when the count is the contract.

open as a page

What does Mockito's verifyNoMoreInteractions do, how does it differ from asserting a mock was never used at all, and what failure does it produce?

level: middleimportance: should knowfreq 44%

basics

~20 s

verifyNoMoreInteractions(mock) asserts that every invocation recorded on the mock has already been verified by earlier verify calls in the test - it closes off leftovers. Asserting the mock was never used at all is a different, unconditional check. Leftovers fail with a no-interactions-wanted error naming the unverified call.

open as a page

CI intermittently fails on assertions written as verify(handler, timeout(50)).handle(event), which always pass on a developer laptop. How do you diagnose that, and when would you replace the timed verification with a CountDownLatch or a polling library such as Awaitility?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A 50 ms budget is a guess about machine speed; loaded CI with fewer cores and GC pauses blows through it. Because timeout returns on success, raising it to a couple of seconds costs nothing and removes the flake. Replace it with a latch or Awaitility when you need a real happens-before edge or must poll state rather than an interaction.

open as a page

A teammate writes verify(mailer, timeout(500).never()).send(any()) in a Mockito test to prove no email is sent. What happens when that test runs, and how should the assertion be written instead?

level: seniorimportance: should knowfreq 25%

basics

~10 s

It does not work as a check: Mockito refuses timeout() combined with never() and throws a friendly-reminder misuse exception. Use verify(mailer, after(500).never()).send(any()), which waits the whole window before concluding nothing was sent.

open as a page

A Mockito verification fails with 'Wanted but not invoked' while another fails with 'Verification failed: too many actual invocations'. What does each message tell you, and how do you work from it to the root cause?

level: seniorimportance: should knowfreq 48%

basics

~20 s

'Wanted but not invoked' means no recorded call matched your description - usually wrong arguments, wrong mock instance, or the code path never ran; the message lists the actual interactions. 'Too many actual invocations' means the method matched more often than the mode allowed, and prints the extra call's stack trace.

open as a page

Order-sensitive mock verification makes a test fail when someone reorders two calls even though observable behaviour is unchanged. How do you decide which orderings are worth asserting across a large test suite?

level: principalimportance: should knowfreq 20%

basics

~20 s

Assert an order only when reversing it is a real defect — correctness, safety or an external protocol depends on it. If you cannot name the bug that reordering causes, the ordering is an implementation detail and asserting it just freezes today's code.

open as a page

What does the only() verification mode assert in Mockito, and how does it differ from a plain single-call verification?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

verify(mock, only()).foo() asserts two things at once: foo() was called exactly once, and it was the only invocation on that mock. A plain verify(mock).foo() checks only the first half - other methods on the mock may also have been called.

open as a page

Inside an ordered Mockito verification, what does the calls(2) mode do that neither times(2) nor atLeast(2) does, and when would you reach for it?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

calls(n) is the non-greedy ordered mode: it consumes exactly n consecutive matching calls and moves on, tolerating further calls of the same method afterwards without marking them verified. times(n) fails if more matching calls follow in range, and atLeast(n) greedily consumes all of them.

open as a page

Mockito's InOrder handle has its own verifyNoMoreInteractions(), and there is also the static Mockito.verifyNoMoreInteractions(mock). How do the two differ, and when does one pass while the other fails?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

inOrder.verifyNoMoreInteractions() only fails if some interaction happened after the last invocation verified through that handle; earlier unverified calls are fine. The static form is order-blind and fails on any unverified invocation on the mock, wherever it sits.

open as a page

When you assert in Mockito that no unverified calls are left on a mock, calls to stubbed methods keep tripping the check. How does ignoreStubs help, and when is exhaustive interaction verification the wrong tool entirely?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

ignoreStubs(mock...) returns the same mocks with their stubbed invocations pre-marked as verified, so an exhaustive check only reports genuinely unexpected calls. It is the wrong tool when the collaborator's full protocol is not what the test is specifying - then a targeted positive and negative assertion pair ages far better.

open as a page

Across a large suite, when is waiting inside a mock verification the right tool at all, versus a sign the production code should expose a seam that makes the test deterministic? How would you set that policy for a team?

level: principalimportance: nice to knowfreq 20%

basics

~20 s

Timed verification is legitimate where asynchrony is the behaviour under test — typically integration-level boundaries. In unit tests it usually means the class hides its executor. Policy: inject execution seams, ban sleeps, allow generous timeouts at boundaries, keep full-wait afters rare and budgeted.

open as a page