Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 · Argument Matchers and Captors

Argument Matchers – any(), eq(), anyString()

Stub and verify without spelling out every value using Mockito argument matchers such as any, anyString, anyInt, eq, isNull and startsWith, and how null is treated.

Until now you passed exact values: when(users.findById(7)) matches only 7. That is often too narrow. A test may not care which id is used, the argument may be an object you cannot easily reproduce (a generated id, a timestamp), or you want one stub to cover a whole range of inputs. Argument matchers replace a literal argument with a rule: "any string", "any integer", "an argument equal to X", "a string that starts with ERR".

Real Mockito code is read-only. Runnable examples use the Mini stand-in from What Is Mockito?, which provides any(), anyString(), anyInt(), eq(), isNull(), startsWith() and argThat() with the same names and the same null rules as Mockito 2 and later.

Matchers in stubbing and verification

Matchers work in both places where arguments appear:

Java
import static org.mockito.ArgumentMatchers.*;      // or: import static org.mockito.Mockito.*;
import static org.mockito.Mockito.*;

when(prices.priceOf(anyString())).thenReturn(10.0);          // any SKU costs 10
verify(mailer).send(eq("[email protected]"), anyString());     // this recipient, any text
verify(audit, never()).record(anyString(), anyInt());        // never recorded, whatever the values

Mockito's own Mockito class extends ArgumentMatchers, so one static import of org.mockito.Mockito.* already gives you every matcher.

The common matchers

Matcher Matches
any() anything, including null
any(Foo.class) any non-null instance of Foo (type checked, null does not match)
anyString(), anyInt(), anyLong(), anyDouble(), anyBoolean() any non-null value of that type
anyList(), anySet(), anyMap(), anyCollection() any non-null collection of that kind
eq(x) a value equal to x; needed when mixing with other matchers (next lesson)
isNull(), notNull(), nullable(Foo.class) null, non-null, or null or a Foo
startsWith("ab"), endsWith("z"), contains("mid"), matches("regex") strings by pattern
same(x) the identical object (==)
argThat(predicate) whatever your predicate accepts (Custom Argument Matchers)

The null rule

Since Mockito 2, typed matchers such as anyString(), anyInt() and any(Foo.class) do not match null. Only any() (with no class) and isNull()/nullable(...) do. If a stub or verification written with anyString() seems to "stop working" for some call, check whether the code passed null.

Try it: stubbing with matchers

Java One stub for many inputs

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.

Look at the two stubs for priceOf: the general anyString() stub comes first and the specific eq("DIAMOND") stub second, so the specific one wins for "DIAMOND" (newest first, see Stubbing Return Values).

Matchers in verification

Verification is where matchers pay off most, because the exact values are often unknowable or irrelevant:

  • a generated id or timestamp: verify(orders).save(any(Order.class));
  • an exact recipient but a free-form body: verify(mailer).send(eq("[email protected]"), anyString());
  • "never called, whatever the arguments": verify(payments, never()).charge(anyString(), anyInt()).
Java Verifying with matchers, and the null rule

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.

Where matchers appear in real projects

  • Loose stubs for collaborators the test does not care about (when(clock.now()).thenReturn(...) needs no matcher, but when(translator.translate(anyString(), anyString())) does).
  • Verification of effects with generated data: ids, timestamps, UUIDs, random tokens.
  • Negative verification with never(): "this must not be called with any arguments".

Do not use matchers everywhere just to avoid thinking about the values. Specific arguments make a test stronger: verify(mailer).send("[email protected]", "Welcome!") proves the right user got the right text, while verify(mailer).send(anyString(), anyString()) only proves that some mail went out. Use loose matchers where the detail is irrelevant, and exact values where it is the point of the test.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which matcher accepts null?

    Since Mockito 2, only any() without a class (and isNull()/nullable()) match null. The typed matchers require a non-null value.
  2. 2. Where can argument matchers be used?

    Matchers replace literal arguments wherever Mockito compares arguments: stubs and verifications.
  3. 3. A call is verify(mailer).send(eq("[email protected]"), anyString()). What does it prove?

    The recipient must be equal to the given address, the text is unconstrained, and verify() still means exactly once.
  4. 4. When should you prefer exact values over matchers?

    Loose matchers make a test weaker. Use exact values where the detail matters and matchers for incidental data.

Summary

  • Matchers replace literal arguments in stubbing and verification: any(), anyString(), anyInt(), eq(), isNull(), startsWith() and more.
  • Typed matchers do not match null; any() and isNull() do.
  • Matchers shine for generated data and for "never called with anything" checks.
  • Use exact values when the value is the point of the test.
  • There is one big rule about mixing matchers with raw values: see the next lesson.

Next: The Matcher Rules