skip to content

Argument Matchers

Matchers like any, eq, isNull and argThat let you stub or verify loosely — under the strict rule that once one argument is a matcher, all of them must be. That all-or-nothing rule is the error people hit and interviewers ask about.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What are argument matchers in Mockito, and why would you use any() or eq() instead of passing a literal value when stubbing or verifying?

level: juniorimportance: must knowfreq 70%

answer

  1. matcher = a rule, not a value (pushed onto a thread-local stack)
  2. any() matches null; any(Foo.class) does not
  3. anyInt/anyString never match null
  4. literal == implicit eq()
  5. use the most specific matcher that fits

basics

~20 s

Argument matchers like any() or eq() tell Mockito how to match the arguments of a call instead of comparing exact values. Use any() when the value doesn't matter and eq(x) when you need a specific value but other arguments use matchers.

solid answer

~40 s

An argument matcher is a placeholder you put where a method argument goes during stubbing (when(...)) or verification (verify(...)) that defines how Mockito decides whether a real call matches. Instead of giving a concrete value, you give a rule: any() matches anything, anyInt()/anyString() match any value of that type (non-null for primitives), eq(x) matches values equal to x, and isNull() matches null. You reach for matchers when the exact argument is irrelevant to the test, hard to reproduce, or generated internally — for example a timestamp or a builder-created object. They keep tests focused on behaviour rather than incidental values. Passing a plain literal is actually an implicit eq() matcher under the hood, so literals and matchers do mix conceptually, but Mockito has a strict rule about mixing them syntactically (covered separately).

go deeper

for a junior

Knows that any() and eq() are placeholders used in when()/verify(), and that any() ignores the value while eq(x) requires a specific one.

for a middle

Distinguishes any() (matches null) from any(Foo.class) (non-null only), knows anyInt/anyString never match null, and picks the most specific matcher.

for a senior

Explains the thread-local-stack mechanism, knows a literal is an implicit eq(), and reasons about when over-matching with any() hides defects.

for a principal

Sets team conventions on matcher specificity vs. brittleness, weighs matcher use against argument captors, and can explain matcher internals when debugging cryptic InvalidUseOfMatchersException failures.

## What a mock and a stub are In unit testing, a **mock** is a fake implementation of a dependency (an interface or class) that records the calls made to it and returns whatever you tell it to. **Mockito** is the most common Java mocking library. You create a mock with `mock(Service.class)`, tell it how to respond with `when(mock.method(...)).thenReturn(...)` (this is **stubbing**), and later assert it was called with `verify(mock).method(...)` (this is **verification**). ## The problem matchers solve When you write `when(repo.findById(42L)).thenReturn(user)`, Mockito records that the stub fires only when `findById` is called with an argument **equal to** `42L`. That exact-value matching is fine when you control and care about the value. But often you don't: maybe the argument is a freshly-generated UUID, the current time, or an object whose `equals` is awkward. In those cases you want to say "match *any* argument" or "match an argument satisfying *this rule*". That rule object is an **argument matcher**. ## How matchers actually work (the mechanism) A matcher is **not** a value. `any()` does not return the argument; it returns a dummy (often `null` or a zero) and, as a side effect, **pushes a matcher object onto an internal thread-local stack** inside Mockito. When you then call the mocked method, Mockito pops those matchers off the stack and associates one with each argument position. This side-effect mechanism is the reason for the strict mixing rule discussed in a related question — Mockito can only tell positions apart by counting pushed matchers. ## The built-in matchers (all static methods of `org.mockito.ArgumentMatchers`) - `any()` — matches anything, **including null** (in modern Mockito). `any(Foo.class)` matches any non-null instance of `Foo` and, importantly, **does not match null**. - `anyInt()`, `anyLong()`, `anyBoolean()`, `anyDouble()`, … — match any value of that **primitive** type; they never match null (a primitive can't be null). - `anyString()` — any non-null String. `anyList()`, `anyMap()`, `anyCollection()` — any non-null collection of that kind. - `eq(value)` — matches arguments that are `.equals(value)`. This is what a plain literal compiles to conceptually. - `isNull()` / `isNotNull()` / `nullable(Class)` — match null, non-null, or "null or an instance of the class". - `argThat(predicate)` — match using a custom rule (covered in its own question). ## When to use which Use the **most specific matcher that still expresses your intent**. If the test genuinely doesn't care about an argument, `any()`/`anyInt()` documents that. If one argument matters and the rest don't, pin the one that matters with `eq(...)` and relax the others with `any...()`. Over-using `any()` everywhere is a smell: it can hide bugs where the code passes the wrong value, because the stub or verification still matches. ## Why a literal is an implicit eq() When you write `verify(mock).save(user)`, Mockito treats `user` as `eq(user)` — it compares with `equals`. This is why you can usually mix literals and matchers conceptually, even though the **syntactic** mixing rule forbids leaving some positions as raw literals once any position uses a matcher. ## Bottom line Matchers let a test assert *behaviour* ("save was called once with this id") without coupling to *incidental values* ("…and exactly this timestamp"), making tests both more robust and more readable — as long as you stay specific enough to still catch real defects.

  • Does any() match a null argument?
    Bare any() matches null in modern Mockito. But any(SomeType.class) matches only non-null instances of that type, so to also accept null you use isNull(), nullable(SomeType.class), or bare any().
  • What is the difference between anyInt() and any(Integer.class)?
    anyInt() matches any int (a primitive, never null). any(Integer.class) matches any non-null Integer object. If the parameter is the boxed Integer and could be null, neither matches null — you'd need isNull()/nullable().

saying these in an interview costs you the question

  • Saying any() returns the actual argument value — it returns a dummy and registers a matcher as a side effect.
  • Claiming any(Foo.class) matches null — it does not; use isNull()/nullable() for that.
  • Thinking anyInt() can match a null Integer — primitives are never null.
  • Using any() everywhere, which hides wrong-value bugs.

context

open as a page

Explain Mockito's rule that if one argument uses a matcher, all arguments must use matchers. Why does this rule exist, and how do you satisfy it for a literal argument?

level: middleimportance: must knowfreq 75%

basics

~20 s

If you use a matcher like any() for one argument of a call, you must use matchers for every argument of that call. For a plain value, wrap it in eq(). Mixing a matcher with a raw literal throws InvalidUseOfMatchersException.

open as a page

How do you correctly match null and nullable arguments in Mockito, and how does that interact with typed any(Class) and primitive matchers?

level: middleimportance: should knowfreq 45%

basics

~20 s

To match a null argument use isNull(); to match null or a value use nullable(Type.class) or bare any(). any(Foo.class) and anyString()/anyInt() do NOT match null, so don't rely on them when the code might pass null.

open as a page

How do you match a complex argument by some of its fields using argThat(), and what are the trade-offs versus ArgumentCaptor?

level: seniorimportance: should knowfreq 55%

basics

~20 s

argThat() lets you pass a custom predicate that decides whether an argument matches — e.g. accept any Order whose total is over 100. Use it for inline rules; use ArgumentCaptor when you want to grab the actual argument and run rich assertions on it.

open as a page

When does heavy use of any() argument matchers weaken a test suite, and how do you decide between permissive matchers, eq()/argThat specificity, and ArgumentCaptor at scale?

level: principalimportance: should knowfreq 35%

basics

~20 s

Using any() for every argument makes tests pass even when the code passes wrong values, so bugs slip through. Match the arguments that carry the test's intent with eq()/argThat, relax only the truly irrelevant ones, and capture when you need detailed checks.

open as a page