Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Verification

Verification Basics with verify()

Use Mockito verify() to assert that a mock was called, with which arguments and how often, and learn what is worth verifying and what is not.

Stubbing prepares what the collaborators answer. Verification checks what the code under test did to them. Some behavior has no return value to assert on: a service that sends an email, saves a record or publishes an event returns void or boolean, and the interesting fact is that the collaborator was called. Mockito mocks remember every call, so after the code under test has run you can ask: "was mailer.send(...) called, and with what?"

Real Mockito code is read-only. Runnable examples use the Mini stand-in from What Is Mockito?. Its failure messages are similar to, not identical with, the real ones.

The basic form

Java
import static org.mockito.Mockito.*;

verify(mailer).send("[email protected]", "Welcome!");

Read it as "verify that mailer received exactly this call, exactly once". verify(mock) returns a special version of the mock, and the method you call on it is not executed but checked against the recorded history. If the check passes, nothing happens (the test continues). If it fails, Mockito throws a MockitoAssertionError subclass whose message explains the difference, so the test fails.

verify(mock) is shorthand for verify(mock, times(1)). Other modes (never(), atLeast(n), ...) have their own lesson: Verification Modes.

Try it: a passing verification

Java verify() after the code under test ran

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the order of events: stub first (if needed), run the code, verify last. Verification always looks back at what already happened; it never predicts the future. Calling verify before the code under test runs is a common beginner mistake and always fails.

When verification fails

The typical failures are a call that never happened, a call with different arguments, and a call that happened more often than expected. In real Mockito the first looks like this (file names and line numbers differ):

TEXT
Wanted but not invoked:
mailer.send("[email protected]", "Welcome!");
-> at SignupServiceTest.newUserGetsAMail(SignupServiceTest.java:31)

Actually, there were zero interactions with this mock.

and, when the mock was called, but with other arguments, Mockito prints "Argument(s) are different!" with the wanted and actual calls one above the other, so you can spot the typo. Read these messages carefully: they are among the best in any test library.

The runnable program below provokes three failures on purpose and prints the stand-in's messages:

Java Reading verification failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The "twice" case previews times(n), which you will meet in the next lesson. Notice how the stand-in lists the actual interactions, which is the most useful part of a failure message.

What to verify and what not to

The power of verify tempts people to verify everything. Resist that. Tests that mirror the implementation line by line break whenever you refactor, even when behavior stays correct. Use these guidelines:

  • Verify interactions that are the point of the code: a message sent, a record saved, an event published, a payment charged. These are outputs of the unit that have no return value.
  • Do not verify calls that only fetch data, such as users.findById(7). If the data were not fetched, your assertions on the result would already fail. Verifying it adds noise and couples the test to how the code finds the data.
  • Prefer asserting on state when you can. If the service returns a value, assert on it with assertEquals. Reserve verify for effects you cannot see in a return value.
  • Verify that something did not happen when it matters: a failed payment must not mark the order paid (never(), next lesson).

A stub plus a verify of the same call is almost always redundant. If you stub existsByEmail to return true and the test then checks the returned value, the code clearly used that stub (and with the strict-stubs extension an unused stub fails the test anyway). Verifying that call again says nothing new.

Stub, act, verify

Arrange Stub what the mocks answer
Act Call the code under test once
Assert Check the result with assertEquals
Verify Check effects with verify()

Verify last, and only effects that matter.

1 / 3

A quick look at argument details

verify(mailer).send("[email protected]", "Welcome!") compares both arguments with equals, just like stubbing. When you want to check only part of a call (for example, "any text") you need argument matchers, which have their own chapter starting with Argument Matchers. To inspect an argument in depth, capture it (ArgumentCaptor).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When in a test do you call verify()?

    verify() checks the recorded history, so the code under test must already have run.
  2. 2. What does verify(mailer).send("a", "b") check?

    verify(mock) means times(1): exactly one matching call, with arguments compared by equals.
  3. 3. Which interaction is usually worth verifying?

    Sending a message is an effect with no return value to assert, so verify is the right tool. Plain lookups are already proven by the result.
  4. 4. A verify fails with 'Wanted but not invoked'. What does this tell you?

    That message means the history has no call matching the wanted one; the actual interactions it lists help you spot the difference.

Summary

  • verify(mock).method(args) checks, after the fact, that exactly one matching call happened (times(1) is the default).
  • Order of a test: stub, act, assert state, verify effects.
  • Verification failures list the wanted call and the actual interactions; read them closely.
  • Verify effects that matter (messages, saves, events, things that must not happen); avoid verifying plain lookups and every internal call.
  • Prefer state assertions when the code returns something.

Next: Verification Modes