0
# Argument Matching
1
2
This section covers flexible argument matching for stubbing and verification, including built-in matchers, custom matchers, and advanced matching patterns.
3
4
**Key Points:**
5
- Since Mockito 2.1.0, type matchers exclude null values - use `isNull()` to match nulls explicitly
6
- Since Mockito 5.0.0, `any()` no longer matches varargs - use `any(Class)` instead
7
- When using argument matchers, **all arguments** must be provided by matchers (or wrapped with `eq()`)
8
- Use primitive-specific matchers (`intThat()`, `booleanThat()`, etc.) to avoid `NullPointerException` from auto-unboxing
9
10
## Basic Argument Matchers
11
12
### Common Type Matchers
13
14
Match arguments by type without specifying exact values.
15
16
**Important Notes:**
17
- Since Mockito 2.1.0, type matchers like `any(Class)` and primitive matchers exclude null values
18
- Since Mockito 5.0.0, `any()` no longer matches varargs - use `any(Class)` instead
19
- For matching null values, use `isNull()` explicitly
20
21
```java { .api }
22
public static <T> T any()
23
public static <T> T any(Class<T> type)
24
public static String anyString()
25
public static int anyInt()
26
public static long anyLong()
27
public static double anyDouble()
28
public static float anyFloat()
29
public static boolean anyBoolean()
30
public static byte anyByte()
31
public static short anyShort()
32
public static char anyChar()
33
```
34
35
**Usage Examples:**
36
37
```java
38
List<String> mockList = mock(List.class);
39
40
// Stub with type matchers
41
when(mockList.get(anyInt())).thenReturn("any element");
42
when(mockList.add(anyString())).thenReturn(true);
43
44
// Use mock
45
mockList.add("hello");
46
mockList.get(5);
47
48
// Verify with type matchers
49
verify(mockList).add(anyString());
50
verify(mockList).get(anyInt());
51
```
52
53
### Collection Matchers
54
55
Match collections and iterables with flexible patterns.
56
57
**Note:** Since Mockito 2.1.0, these matchers only accept non-null instances. Use `isNull()` to explicitly match null values.
58
59
```java { .api }
60
public static <T> Collection<T> anyCollection()
61
public static <T> List<T> anyList()
62
public static <T> Set<T> anySet()
63
public static <K, V> Map<K, V> anyMap()
64
public static <T> Iterable<T> anyIterable()
65
```
66
67
**Usage Examples:**
68
69
```java
70
DataService mockService = mock(DataService.class);
71
72
// Stub with collection matchers
73
when(mockService.processItems(anyList())).thenReturn("processed");
74
when(mockService.processMap(anyMap()))
75
.thenReturn("map processed");
76
when(mockService.processIterable(anyIterable())).thenReturn("iterable processed");
77
78
// Use mock
79
mockService.processItems(Arrays.asList("a", "b", "c"));
80
mockService.processMap(Map.of("key", 123));
81
mockService.processIterable(Set.of("x", "y", "z"));
82
83
// Verify with collection matchers
84
verify(mockService).processItems(anyList());
85
verify(mockService).processMap(anyMap());
86
verify(mockService).processIterable(anyIterable());
87
```
88
89
## Exact Value Matchers
90
91
### Equality and Null Matchers
92
93
Match specific values or null/non-null conditions.
94
95
```java { .api }
96
// Equality matchers for all types
97
public static <T> T eq(T value)
98
public static boolean eq(boolean value)
99
public static byte eq(byte value)
100
public static char eq(char value)
101
public static double eq(double value)
102
public static float eq(float value)
103
public static int eq(int value)
104
public static long eq(long value)
105
public static short eq(short value)
106
107
// Advanced equality matchers
108
public static <T> T refEq(T value, String... excludeFields)
109
public static <T> T same(T value)
110
111
// Null/not-null matchers
112
public static <T> T isNull()
113
public static <T> T isNull(Class<T> type)
114
public static <T> T isNotNull()
115
public static <T> T isNotNull(Class<T> type)
116
public static <T> T notNull()
117
public static <T> T notNull(Class<T> type)
118
119
// Type and nullability matchers
120
public static <T> T isA(Class<T> type)
121
public static <T> T nullable(Class<T> clazz)
122
```
123
124
**Usage Examples:**
125
126
```java
127
UserService mockService = mock(UserService.class);
128
129
// Exact value matching
130
when(mockService.findUser(eq("john"))).thenReturn(johnUser);
131
when(mockService.findUser(eq("jane"))).thenReturn(janeUser);
132
133
// Null matchers
134
when(mockService.findUser(isNull())).thenThrow(IllegalArgumentException.class);
135
when(mockService.findUser(isNull(String.class))).thenThrow(IllegalArgumentException.class);
136
when(mockService.createUser(notNull())).thenReturn(true);
137
when(mockService.createUser(notNull(User.class))).thenReturn(true);
138
139
// Nullable matcher (accepts null or specified type)
140
when(mockService.processUser(nullable(User.class))).thenReturn("processed");
141
142
// Type checking
143
when(mockService.process(isA(AdminUser.class))).thenReturn("admin");
144
145
// Reference equality
146
User specificUser = new User("test");
147
when(mockService.updateUser(same(specificUser))).thenReturn(true);
148
149
// Reflection equality (ignoring specific fields)
150
User template = new User("john", "john@example.com");
151
when(mockService.createUser(refEq(template, "id", "createdAt")))
152
.thenReturn(true);
153
```
154
155
## String Matchers
156
157
### String Pattern Matching
158
159
Match strings with patterns and conditions.
160
161
```java { .api }
162
public static String startsWith(String prefix)
163
public static String endsWith(String suffix)
164
public static String contains(String substring)
165
public static String matches(String regex)
166
public static String matches(Pattern pattern)
167
```
168
169
**Usage Examples:**
170
171
```java
172
EmailService mockService = mock(EmailService.class);
173
174
// String pattern matching
175
when(mockService.sendEmail(startsWith("urgent:"))).thenReturn(true);
176
when(mockService.sendEmail(endsWith("@company.com"))).thenReturn(true);
177
when(mockService.sendEmail(contains("password"))).thenReturn(false);
178
179
// Regex matching
180
when(mockService.validateEmail(matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")))
181
.thenReturn(true);
182
183
// Pattern matching
184
Pattern emailPattern = Pattern.compile(".*@.*\\.com");
185
when(mockService.validateEmail(matches(emailPattern))).thenReturn(true);
186
187
// Verify with string matchers
188
verify(mockService).sendEmail(startsWith("urgent:"));
189
verify(mockService).validateEmail(matches(".*@.*"));
190
```
191
192
## Custom Argument Matchers
193
194
### ArgumentMatcher Interface
195
196
Create custom matching logic for complex scenarios.
197
198
```java { .api }
199
public static <T> T argThat(ArgumentMatcher<T> matcher)
200
public static <T> T assertArg(Consumer<T> consumer)
201
public static <T> T assertArg(ThrowingConsumer<T> consumer)
202
203
// Primitive-specific matchers to avoid NullPointerException
204
public static boolean booleanThat(ArgumentMatcher<Boolean> matcher)
205
public static byte byteThat(ArgumentMatcher<Byte> matcher)
206
public static char charThat(ArgumentMatcher<Character> matcher)
207
public static short shortThat(ArgumentMatcher<Short> matcher)
208
public static int intThat(ArgumentMatcher<Integer> matcher)
209
public static long longThat(ArgumentMatcher<Long> matcher)
210
public static float floatThat(ArgumentMatcher<Float> matcher)
211
public static double doubleThat(ArgumentMatcher<Double> matcher)
212
213
interface ArgumentMatcher<T> {
214
boolean matches(T argument);
215
default String toString() {
216
return "custom matcher";
217
}
218
}
219
```
220
221
**Usage Examples:**
222
223
```java
224
List<String> mockList = mock(List.class);
225
226
// Custom matcher using lambda
227
when(mockList.add(argThat(s -> s.length() > 5))).thenReturn(true);
228
229
// Custom matcher with description
230
ArgumentMatcher<String> longString = new ArgumentMatcher<String>() {
231
@Override
232
public boolean matches(String argument) {
233
return argument != null && argument.length() > 10;
234
}
235
236
@Override
237
public String toString() {
238
return "string longer than 10 characters";
239
}
240
};
241
242
when(mockList.add(argThat(longString))).thenReturn(true);
243
244
// Using method reference
245
when(mockList.add(argThat(String::isEmpty))).thenReturn(false);
246
247
// Complex object matching
248
User expectedUser = new User("john", "john@example.com");
249
when(userService.createUser(argThat(user ->
250
user.getName().equals("john") &&
251
user.getEmail().contains("@") &&
252
user.getAge() >= 18
253
))).thenReturn(true);
254
```
255
256
### AdditionalMatchers Utility
257
258
Additional matchers for numeric and array comparisons.
259
260
```java { .api }
261
public static <T extends Comparable<T>> T geq(T value)
262
public static <T extends Comparable<T>> T leq(T value)
263
public static <T extends Comparable<T>> T gt(T value)
264
public static <T extends Comparable<T>> T lt(T value)
265
public static <T> T[] aryEq(T[] value)
266
public static <T> T and(T first, T second)
267
public static <T> T or(T first, T second)
268
public static <T> T not(T matcher)
269
```
270
271
**Usage Examples:**
272
273
```java
274
NumberService mockService = mock(NumberService.class);
275
276
// Numeric comparisons
277
when(mockService.process(gt(100))).thenReturn("large");
278
when(mockService.process(lt(10))).thenReturn("small");
279
when(mockService.process(geq(50))).thenReturn("medium+");
280
281
// Array equality
282
int[] expectedArray = {1, 2, 3};
283
when(mockService.processArray(aryEq(expectedArray))).thenReturn(true);
284
285
// Logical combinations
286
when(mockService.process(and(gt(10), lt(100)))).thenReturn("medium");
287
when(mockService.process(or(eq(0), eq(1)))).thenReturn("binary");
288
when(mockService.process(not(eq(42)))).thenReturn("not answer");
289
```
290
291
## Advanced Matching Patterns
292
293
### Capturing Arguments with Matchers
294
295
Combine argument capturing with flexible matching.
296
297
```java { .api }
298
public static <T> T assertArg(Consumer<T> assertion)
299
```
300
301
**Usage Examples:**
302
303
```java
304
UserService mockService = mock(UserService.class);
305
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
306
307
// Use mock
308
User newUser = new User("alice", "alice@example.com");
309
mockService.createUser(newUser);
310
311
// Capture and assert
312
verify(mockService).createUser(userCaptor.capture());
313
User capturedUser = userCaptor.getValue();
314
assertEquals("alice", capturedUser.getName());
315
assertTrue(capturedUser.getEmail().contains("@"));
316
317
// Using assertArg - more direct approach for assertions
318
verify(mockService).createUser(assertArg(user -> {
319
assertEquals("alice", user.getName());
320
assertTrue(user.getEmail().contains("@"));
321
assertNotNull(user.getId());
322
}));
323
324
// Using assertArg with ThrowingConsumer for checked exceptions
325
verify(fileService).processFile(assertArg(file -> {
326
assertTrue(file.exists());
327
assertTrue(file.canRead());
328
// Can throw IOException here
329
}));
330
331
// Primitive-specific matchers to avoid NullPointerException on auto-unboxing
332
when(calculator.calculate(intThat(x -> x > 0))).thenReturn("positive");
333
when(validator.isValid(booleanThat(b -> b == true))).thenReturn("confirmed");
334
when(processor.process(doubleThat(d -> d >= 0.0 && d <= 1.0))).thenReturn("normalized");
335
```
336
337
### Matcher Combination Strategies
338
339
Complex matching patterns using multiple matchers.
340
341
**Usage Examples:**
342
343
```java
344
SearchService mockService = mock(SearchService.class);
345
346
// Combining multiple conditions
347
when(mockService.search(
348
argThat(query -> query.length() > 3),
349
argThat(filters -> filters.containsKey("category")),
350
anyInt()
351
)).thenReturn(searchResults);
352
353
// Mixed exact and flexible matching
354
when(mockService.searchUsers(
355
eq("active"),
356
argThat(age -> age >= 18 && age <= 65),
357
anyString(),
358
isNotNull()
359
)).thenReturn(activeAdults);
360
361
// Nested object matching
362
when(mockService.processRequest(argThat(request ->
363
request.getUser() != null &&
364
request.getUser().isActive() &&
365
request.getParameters().size() > 0
366
))).thenReturn(successResponse);
367
```
368
369
## Common Matching Pitfalls
370
371
### Matcher Mixing Rules
372
373
Understanding when and how to mix matchers with exact values.
374
375
**Incorrect Usage:**
376
```java
377
// DON'T MIX matchers and exact values
378
when(mockList.subList(anyInt(), 10)).thenReturn(sublist); // WRONG!
379
```
380
381
**Correct Usage:**
382
```java
383
// Use matchers for all arguments or none
384
when(mockList.subList(anyInt(), anyInt())).thenReturn(sublist); // CORRECT
385
when(mockList.subList(0, 10)).thenReturn(sublist); // ALSO CORRECT
386
387
// Or use eq() to make exact values explicit
388
when(mockList.subList(anyInt(), eq(10))).thenReturn(sublist); // CORRECT
389
```
390
391
### Null Handling in Matchers
392
393
Proper handling of null values in custom matchers.
394
395
```java
396
// Null-safe custom matcher
397
ArgumentMatcher<String> safeStringMatcher = s ->
398
s != null && s.trim().length() > 0;
399
400
// Or more explicit
401
ArgumentMatcher<User> activeUserMatcher = user -> {
402
if (user == null) return false;
403
return user.isActive() && user.getName() != null;
404
};
405
406
// Use nullable() matcher when null OR a specific type is acceptable
407
when(userService.findUser(nullable(String.class))).thenReturn(defaultUser);
408
// This matches both null and any non-null String
409
```