ArgumentMatchers
- Java course
- Advanced
- Lesson 53/82
- 5 min
Learn flexible arguments with ArgumentMatchers.
ArgumentMatchers
With ArgumentMatchers mock calls are matched flexibly. any() matches any value, eq("x") matches a specific value, anyInt() matches any integer.
when(repo.findById(anyInt()))
.thenReturn(new User("Alex"));
verify(mail).send(eq("Alex"));This lets you specify a category instead of a fixed value. When a matcher is used, all arguments must be matchers; mixed usage is not allowed. This rule must be kept in mind.
The matcher mix rule
If you use a matcher in a call, all arguments must be matchers. You cannot mix a fixed value with a matcher. Use eq() for fixed values.
// Valid:
verify(mail).send(eq("Alex"));
// Invalid (mixed):
// verify(mail).send("Alex", anyString());This rule comes from Mockito's matching mechanism. By wrapping fixed values with eq() you comply with the rule. This is a common trap for beginners.
Practice Build matcher logic
Define a Matcher class with boolean matchesAny(int v) that always returns true and boolean matchesEq(int v, int target) that returns v == target. In a MatcherDemo class write main; print the results of matchesAny(5) and matchesEq(5, 5) on separate lines (true, true).
Starter code
// Define the Matcher class (matchesAny and matchesEq methods)
// Write main in MatcherDemo; print the two results on separate linesSample solution
class Matcher {
boolean matchesAny(int v) {
return true;
}
boolean matchesEq(int v, int target) {
return v == target;
}
}
class MatcherDemo {
public static void main(String[] args) {
Matcher m = new Matcher();
System.out.println(m.matchesAny(5));
System.out.println(m.matchesEq(5, 5));
}
}Expected output
true true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the anyInt call
when(repo.findById(____)).thenReturn(new User("Ayşe"));
when(repo.findById(anyInt())).thenReturn(new User("Ayşe"));
Explanation: anyInt() matches any integer.
2 If you use any() in a call, how should the other arguments be?
- All arguments must be matchers Correct answer
- They can be fixed values
- They must be Strings only
- They can be left empty
Explanation: If you use a matcher, all arguments must be matchers.
3 Match the matchers
| Term | Meaning |
|---|---|
any() |
Any object |
anyInt() |
Any integer |
eq("x") |
A specific value |
anyString() |
Any string |