Sr Technical Content Strategist and Team Lead

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.
org.mockito.ArgumentMatchers and work only inside when(), verify(), and related stubbing helpers such as doNothing().when().eq() instead of passing raw values.anyString(), anyInt(), anyList()) over raw any() for primitives and references so you avoid null/unboxing surprises.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.5.14.2 and JUnit Jupiter 5.10.2.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.*;
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.
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.
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
}
}
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.
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));
eq(), eq(1), or eq("hello").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 |
any() and any(Class) for type-based matchingany() 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);
eq() to match exact values inside matcher chainsWhen 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)).
anyString(), anyInt(), anyList(), and other typed matchersTyped 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().
isNull() and isNotNull()when(mockFoo.bool(isNull(), anyInt(), isNotNull())).thenReturn(true);
assertTrue(mockFoo.bool(null, 1, "payload"));
contains(), startsWith(), and endsWith() for string matchingwhen(mockFoo.bool(startsWith("ERR"), anyInt(), any())).thenReturn(false);
mockFoo.bool("ERR-404", 0, null);
verify(mockFoo).bool(contains("ERR"), anyInt(), any());
any() and eq() togetherFoo 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.
For void methods, use doNothing() so matchers work the same way:
doNothing().when(mockFoo).log(anyString());
mockFoo.log("ready");
verify() for behavior verificationArgument matchers work only with verify() (and stubbing APIs), not as general boolean checks.
verify(mockFoo, atLeastOnce()).bool(anyString(), anyInt(), any(Object.class));
verify(mockFoo).bool(eq("false"), anyInt(), any(Object.class));
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());
ArgumentCaptorArgumentCaptor 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.
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());
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());
| 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 |
Implement org.mockito.ArgumentMatcher<T> when built-in matchers are not enough. Register the logic with argThat().
import org.mockito.ArgumentMatcher;
public class PremiumOrderMatcher implements ArgumentMatcher<Order> {
@Override
public boolean matches(Order order) {
return order != null && order.getTotalCents() >= 10_000;
}
}
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;
}
}
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.
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.
Always convert literals with eq() when any sibling parameter uses a matcher.
String value = anyString(); // wrong: matcher used outside stub/verify
Matchers must appear directly inside the mocked method call passed to when() or verify().
any() and masking real bugsPrefer exact values for business-critical parameters (IDs, currencies). Use matchers to remove noise, not to skip important assertions.
Hamcrest matchersMockito 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()) |
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.
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.
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.
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.
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.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.