Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 · Argument Matchers and Captors

The Matcher Rules – All or None, and eq()

Learn the all-or-none rule for Mockito argument matchers, how eq() fixes mixed arguments, why misplaced matchers leak, and how to avoid NPEs with primitives.

Almost everyone meets this Mockito error sooner or later:

TEXT
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
...
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

It looks scary, but there is one simple rule behind it, and once you know why the rule exists you will not forget it. This lesson explains the rule, the fix, and two related traps: matchers used in the wrong place, and matchers on primitive parameters.

Real Mockito messages and code are read-only. The runnable examples use the Mini stand-in from What Is Mockito?, which enforces the same rule (its error text is similar, not identical).

The rule: all arguments or none

In one call, either every argument is a matcher, or none is. Mixing is not allowed:

Java
when(clamp.limit(anyInt(), "cm"))       // WRONG: matcher plus raw value
when(clamp.limit(anyInt(), eq("cm")))   // RIGHT: both are matchers
when(clamp.limit(5, "cm"))              // RIGHT: no matchers at all

If you want "any number, but exactly "cm"", wrap the exact value in eq(...). eq is the matcher that means "equal to this value", and it exists precisely so that raw values can be mixed with other matchers.

Why the rule exists

Matchers are not objects you pass in. Calling anyInt() does not create a rule that travels with the argument; it pushes a rule onto a hidden, per-thread stack and returns a dummy value (0). When the mock method is called a moment later, Mockito looks at the stack, takes the matchers it finds, and uses them for that call.

flowchart LR
    A["anyInt() pushes<br/>matcher 1, returns 0"] --> B["eq(cm) pushes<br/>matcher 2, returns cm"]
    B --> C["mock.limit(0, cm)<br/>is called"]
    C --> D["Mockito pops 2 matchers<br/>for 2 arguments"]
    D --> E["Stub is registered<br/>with the matchers"]

Matchers wait on a stack until the next mock call consumes them. The dummy return values only exist to make the call compile.

Now the rule is obvious: if the call has two arguments and the stack holds only one matcher, Mockito cannot know which argument the matcher belongs to. Was "cm" raw, or was it the first argument? It refuses to guess and fails with InvalidUseOfMatchersException.

Try it: mixing, and the fix

Java The all-or-none 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.

Trap 1: matchers outside stubbing and verification

Because matchers sit on a hidden stack, using one anywhere except as an argument of a stubbed or verified call leaves a matcher behind. The leftover is picked up by the next mock call, possibly many lines later and in a different test, so the error appears in an unrelated place.

Java
String name = anyString();                 // WRONG: nobody consumes this matcher
...
when(repo.find(42, "user")).thenReturn(u);   // fails here, with a confusing message

Another classic: using a matcher as an argument of a call on a real object, realList.add(anyString()). The real add does not consume the matcher either. Even worse, if the next call happens to have the same number of arguments as there are leftover matchers, no error is raised at all and the stale matcher silently changes that call. Fix: put matchers only inside the parentheses of the mock call you are stubbing or verifying, and never keep them in variables or pass them to helper methods that call real code. (The JUnit extension and Mockito.validateMockitoUsage() help to detect leftovers early.)

Java A matcher left on the stack

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.

Trap 2: primitives and null

any() returns null as its dummy value. If the parameter type is a primitive (int, long, boolean), the compiler unboxes that null and throws a NullPointerException before Mockito even sees the call:

Java
when(counter.add(any())).thenReturn(1);      // NPE: unboxing null to int
when(counter.add(anyInt())).thenReturn(1);   // RIGHT: anyInt() returns 0

So for primitive parameters always use the typed matcher (anyInt(), anyLong(), anyBoolean(), ...). For object parameters, any(Foo.class) or any() both work; remember that any(Foo.class) rejects null whereas any() accepts it.

Java any() with a primitive parameter

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.

A checklist for matcher problems

  1. Count the arguments: are all of them matchers (use eq(...) for exact values) or none?
  2. Is every matcher inside the parentheses of a mock call that is being stubbed or verified? No variables, no real objects, no helper methods that call real code.
  3. Are you using anyInt()-style matchers for primitive parameters?
  4. Did a failure in an earlier line leave a matcher behind? Run the test alone: if it passes, the previous test leaked.
  5. For doReturn/doThrow stubbing, the matchers go on the call after when(mock), as in doThrow(e).when(mailer).send(anyString(), eq("x")).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which stubbing is valid?

    Either all arguments are matchers or none. eq(...) wraps an exact value so it can sit next to other matchers.
  2. 2. Why does Mockito reject mixed matchers and raw values?

    A matcher only pushes a rule on a hidden stack. With fewer matchers than arguments the positions are ambiguous, so Mockito fails.
  3. 3. Why does when(counter.add(any())) throw a NullPointerException for add(int)?

    any() returns null as its dummy value. Use anyInt() for primitive parameters.
  4. 4. What is a typical symptom of a matcher used outside a mock call?

    The unused matcher stays on the stack and is picked up by the next mock call, so the error appears away from the mistake.

Summary

  • In one call, use matchers for all arguments or for none; wrap exact values in eq(...).
  • Matchers push rules onto a hidden per-thread stack consumed by the next mock call, which explains the rule.
  • Use matchers only inside stubbed or verified mock calls; leftovers break later, unrelated calls.
  • Use anyInt(), anyLong(), anyBoolean() for primitive parameters, because any() returns null.

Next: Custom Argument Matchers