惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
量子位
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
博客园 - Franky
罗磊的独立博客
宝玉的分享
宝玉的分享
博客园_首页
腾讯CDC
The GitHub Blog
The GitHub Blog
D
DataBreaches.Net
IT之家
IT之家
D
Docker
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
V
V2EX
月光博客
月光博客
N
Netflix TechBlog - Medium
爱范儿
爱范儿
I
InfoQ
P
Proofpoint News Feed

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu
Mockito Argument Matchers: any(), eq() and More
Anish Singh Walia · 2022-08-04 · via DigitalOcean Community Tutorials

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
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

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.