Report this

What is the reason for this report?

Mockito Argument Matchers: any(), eq() and More

Updated on May 19, 2026
Anish Singh Walia

By Anish Singh Walia

Sr Technical Content Strategist and Team Lead

Mockito Argument Matchers: any(), eq() and More

Mockito argument matchers let you stub and verify method calls without hard-coding every Mockito argument value. When you pair matchers with when() and verify(), you can express rules such as “any string” or “this exact ID” while keeping tests readable. This guide walks through built-in matchers, the consistency rule that prevents InvalidUseOfMatchersException, ArgumentCaptor, and custom ArgumentMatcher implementations using current Mockito 5.x APIs with JUnit 5.

Key takeaways

  • Mockito argument matchers live in org.mockito.ArgumentMatchers and work only inside when(), verify(), and related stubbing helpers such as doNothing().when().
  • If one argument uses a matcher, every argument in that call must use a matcher. Wrap literals with eq() instead of passing raw values.
  • Prefer typed matchers (anyString(), anyInt(), anyList()) over raw any() for primitives and references so you avoid null/unboxing surprises.
  • Use ArgumentCaptor when you need to inspect what was passed after the call. Use argThat() with a custom ArgumentMatcher when you need reusable matching logic inline.
  • Matchers record expectations on an internal stack and return dummy values, so never call them outside a stubbing or verification statement.

Prerequisites

  1. Java 11 or newer. If you need a local runtime, follow How To Install Java with Apt on Ubuntu.
  2. A Maven or Gradle project with JUnit 5 and Mockito 5.x. The examples below use Mockito 5.14.2 and JUnit Jupiter 5.10.2.
  3. Familiarity with basic mocks from Mockito Mock Examples and verification from Mockito Verify.
  4. Optional background: JUnit 5 Tutorial and the broader Mockito Tutorial.

Maven test dependencies:

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.10.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>5.14.2</version>
  <scope>test</scope>
</dependency>

Import matchers statically in test classes:

import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

What are Mockito argument matchers?

Mockito argument matchers are helper methods that describe flexible conditions for method parameters during stubbing or verification. Instead of matching with equals() on exact values, you can accept any String, any positive int, or a custom domain rule.

How argument matchers fit into the Mockito framework

Mockito records matchers on an internal stack while you build a stub or verification. Methods such as anyInt() return safe dummy values (for example 0 for anyInt()) so the Java compiler accepts the expression inside when(mock.get(anyInt())). The real matching happens when Mockito replays the recorded matchers against actual invocation arguments. Official reference: ArgumentMatchers Javadoc.

When to use matchers vs exact values

Use exact values (or eq()) when the test cares about one specific input. Use matchers when the value is irrelevant, varies across cases, or follows a pattern (type, range, substring). Overusing any() can hide bugs, so default to exact values and reach for matchers when they reduce duplication.

Sample class used throughout this tutorial:

public class Foo {
    public boolean bool(String str, int i, Object obj) {
        return false;
    }

    public int in(boolean b, java.util.List<String> strs) {
        return 0;
    }

    public int bar(byte[] bytes, String[] s, int i) {
        return 0;
    }

    public void log(String message) {
        // no-op
    }
}

The argument matcher consistency rule

Mockito requires that either all arguments in a stubbing or verification use matchers, or none do. Mixing a matcher with a raw literal triggers InvalidUseOfMatchersException.

Why you cannot mix matchers and exact values

Matchers and literals follow different code paths inside Mockito. A call like when(mock.bool(anyString(), 1, any())) is invalid because 1 is a raw value while the other parameters use matchers.

Incorrect:

when(mockFoo.bool(anyString(), 1, any(Object.class))).thenReturn(true); // throws

Correct:

when(mockFoo.bool(anyString(), eq(1), any(Object.class))).thenReturn(true);

The same rule applies to verify():

verify(mockFoo).bool(eq("hello"), anyInt(), any(Object.class));

How to fix InvalidUseOfMatchersException

  1. Wrap every literal with eq(), eq(1), or eq("hello").
  2. Or remove all matchers and pass only concrete values.
  3. Never store matcher results in variables and reuse them across stubbings.

Built-in argument matchers in Mockito

The table below summarizes commonly used matchers in Mockito 5.x. For null references, typed matchers such as anyString() do not match null; use isNull() or isNotNull() instead.

Matcher Accepted types Null behavior Typical use case
any() Any reference, varargs Allows null Loose reference matching
any(Class<T>) Type T Excludes null Type-safe object matching
eq(value) Same type as value Follows equals() Exact value inside matcher chains
anyString() String Excludes null Any non-null string
anyInt() int or Integer Excludes null wrapper Primitive or boxed int
anyList() List Excludes null Any non-null list
isNull() / isNotNull() Reference types Explicit null checks Nullable parameters
contains(), startsWith(), endsWith() String Excludes null Partial string matching

Using any() and any(Class) for type-based matching

any() matches any reference including null (and supports varargs). any(Foo.class) performs a type check and rejects null. Prefer any(Class) when clarity matters.

Foo mockFoo = mock(Foo.class);
when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true);

assertTrue(mockFoo.bool("A", 1, "A"));
assertTrue(mockFoo.bool("B", 10, new Object()));

For arrays, pass the array class:

when(mockFoo.bar(any(byte[].class), any(String[].class), anyInt())).thenReturn(1);

Using eq() to match exact values inside matcher chains

When any parameter uses a matcher, wrap specific values with eq():

when(mockFoo.bool(eq("false"), anyInt(), any(Object.class))).thenReturn(false);
assertFalse(mockFoo.bool("false", 10, new Object()));

Without other matchers, you may pass literals directly: when(mockFoo.bool("false", 10, obj)).

Using anyString(), anyInt(), anyList(), and other typed matchers

Typed matchers improve readability and avoid autoboxing pitfalls on primitives:

when(mockFoo.in(anyBoolean(), anyList())).thenReturn(10);

Collections and maps also have anySet(), anyMap(), and anyCollection().

Using isNull() and isNotNull()

when(mockFoo.bool(isNull(), anyInt(), isNotNull())).thenReturn(true);
assertTrue(mockFoo.bool(null, 1, "payload"));

Using contains(), startsWith(), and endsWith() for string matching

when(mockFoo.bool(startsWith("ERR"), anyInt(), any())).thenReturn(false);
mockFoo.bool("ERR-404", 0, null);
verify(mockFoo).bool(contains("ERR"), anyInt(), any());

Using argument matchers with when() for stubbing

Stubbing with any() and eq() together

Foo mockFoo = mock(Foo.class);
when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true);
when(mockFoo.bool(eq("false"), anyInt(), any(Object.class))).thenReturn(false);

Stubbing is evaluated in declaration order; the most specific stub should appear last if patterns overlap.

Stubbing methods with multiple parameters (void methods)

For void methods, use doNothing() so matchers work the same way:

doNothing().when(mockFoo).log(anyString());
mockFoo.log("ready");

Using argument matchers with verify() for behavior verification

Argument matchers work only with verify() (and stubbing APIs), not as general boolean checks.

Verifying a method was called with specific argument types (parameter types)

verify(mockFoo, atLeastOnce()).bool(anyString(), anyInt(), any(Object.class));
verify(mockFoo).bool(eq("false"), anyInt(), any(Object.class));

Combining verify() with times(), never(), and atLeast()

verify(mockFoo, times(1)).log(anyString());
verify(mockFoo, never()).bool(eq("skip"), anyInt(), any());
verify(mockFoo, atLeast(0)).in(anyBoolean(), anyList());

To assert call order, use InOrder:

InOrder inOrder = inOrder(mockFoo);
inOrder.verify(mockFoo).log(anyString());
inOrder.verify(mockFoo).bool(anyString(), anyInt(), any());

Capturing arguments with ArgumentCaptor

ArgumentCaptor records arguments passed to a mock so you can assert on them after the fact. It complements matchers: matchers express acceptance rules; captors inspect actual values.

When to use ArgumentCaptor instead of a matcher

Use a captor when you need multiple assertions on the same object after invocation (fields, size, derived values). Use matchers when a predicate is enough during stubbing or verification.

ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
mockFoo.log("shipped");
verify(mockFoo).log(messageCaptor.capture());
assertEquals("shipped", messageCaptor.getValue());

ArgumentCaptor with single and multiple invocations

mockFoo.log("first");
mockFoo.log("second");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockFoo, times(2)).log(captor.capture());
assertEquals(List.of("first", "second"), captor.getAllValues());

ArgumentCaptor vs custom ArgumentMatcher

Approach Best for Trade-off
ArgumentCaptor Inspecting real argument instances after the call Extra verify step, not for stubbing return values
argThat(ArgumentMatcher) Reusable inline rules during stub/verify Less visibility into actual values unless verification fails
eq() / typed any*() Simple, fast tests Less expressive for complex domain rules

Writing a custom ArgumentMatcher

Implement org.mockito.ArgumentMatcher<T> when built-in matchers are not enough. Register the logic with argThat().

Implementing the ArgumentMatcher interface

import org.mockito.ArgumentMatcher;

public class PremiumOrderMatcher implements ArgumentMatcher<Order> {
    @Override
    public boolean matches(Order order) {
        return order != null && order.getTotalCents() >= 10_000;
    }
}

Custom matcher example with a domain object

public class Order {
    private final int totalCents;
    public Order(int totalCents) { this.totalCents = totalCents; }
    public int getTotalCents() { return totalCents; }
}

public class OrderService {
    public boolean isPremium(Order order) {
        return order != null && order.getTotalCents() >= 10_000;
    }
}

Registering and using a custom matcher in tests

OrderService service = mock(OrderService.class);
when(service.isPremium(argThat(new PremiumOrderMatcher()))).thenReturn(true);
assertTrue(service.isPremium(new Order(15_000)));

Lambda form (Java 8+):

when(service.isPremium(argThat(o -> o.getTotalCents() > 5_000))).thenReturn(true);

See ArgumentMatcher Javadoc for design notes from the Mockito team.

Mockito AdditionalMatchers

org.mockito.AdditionalMatchers provides numeric comparisons and array equality helpers:

import static org.mockito.AdditionalMatchers.*;

when(mockFoo.bar(any(byte[].class), aryEq(new String[] { "A", "B" }), gt(10))).thenReturn(11);

assertEquals(11, mockFoo.bar("abc".getBytes(), new String[] { "A", "B" }, 20));

Other helpers include lt(), or(), and(), and not() for composed conditions.

Common mistakes and how to avoid them

Mixing matchers and raw values

Always convert literals with eq() when any sibling parameter uses a matcher.

Using argument matchers outside of when() or verify()

String value = anyString(); // wrong: matcher used outside stub/verify

Matchers must appear directly inside the mocked method call passed to when() or verify().

Overusing any() and masking real bugs

Prefer exact values for business-critical parameters (IDs, currencies). Use matchers to remove noise, not to skip important assertions.

Mockito argument matchers vs Hamcrest matchers

Mockito decoupled from Hamcrest in Mockito 2.1. To use Hamcrest, add the mockito-hamcrest artifact and call MockitoHamcrest.argThat(org.hamcrest.Matcher) instead of the deprecated org.mockito.Matchers APIs. For most projects, Mockito built-ins plus argThat(ArgumentMatcher) stay simpler and avoid an extra dependency.

Tool Entry point When to choose
Mockito ArgumentMatchers any(), eq(), contains() Default choice for Mockito tests
Custom ArgumentMatcher + argThat() argThat(predicate) Domain-specific rules shared across tests
Hamcrest via MockitoHamcrest MockitoHamcrest.argThat(hasItem(...)) Existing Hamcrest assertions you already maintain

Choosing the right tool for the job?

Need Use
Ignore a parameter value anyString(), anyInt(), any(MyDto.class)
One exact value among matchers eq("literal")
Inspect what was passed ArgumentCaptor
Complex reusable rule Custom ArgumentMatcher via argThat()
Void method stub doNothing().when(mock).method(any())

FAQs

1. What are argument matchers in Mockito?

Argument matchers are static methods such as anyString(), eq(), and argThat() that tell Mockito how to compare parameters during stubbing or verification. They allow flexible matching when exact values are unknown or unimportant. If you use a matcher for one parameter, every parameter in that invocation must use a matcher.

2. What is the difference between eq() and any()?

eq(value) requires an argument equal to value according to equals() (or == for primitives). any() and typed variants like anyString() accept a wide range of inputs that satisfy type or substring rules. Use eq() when only one specific input should match; use any*() when the precise value does not matter.

3. When using matchers, do all arguments have to use matchers?

Yes. Mockito enforces matcher consistency on each stubbing or verify() call. Mixing anyString() with a raw literal causes InvalidUseOfMatchersException. Wrap literals with eq() or remove matchers entirely for that call.

4. When should I use eq() in Mockito?

Use eq() when at least one other parameter in the same call already uses a matcher and you need an exact value for this parameter. You can omit eq() when every argument is a plain literal and no matchers are present.

5. What does Mockito any() do?

any() matches any object reference (including null) for reference parameters. Typed alternatives such as anyInt() or any(Order.class) restrict matches to primitives or instances of a class and, since Mockito 2.1.0, exclude null for those typed matchers. Prefer typed matchers for clarity and safer tests.

Conclusion

Mockito argument matchers help you write focused unit tests by stubbing and verifying flexible parameter rules with any(), eq(), typed matchers, ArgumentCaptor, and custom ArgumentMatcher implementations. Remember the all-or-nothing matcher rule, favor typed matchers for primitives and collections, and reach for captors when you need to inspect real argument state after the call.

Continue building with DigitalOcean

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Content Strategist and Team Lead
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Category:

Still looking for an answer?

Was this helpful?
Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.

Dark mode is coming soon.