A comprehensive Java mocking framework that enables developers to create test doubles for unit testing.
—
Argument matchers provide flexible matching for method arguments during stubbing and verification. They allow you to specify patterns instead of exact values.
public static <T> T any();
public static <T> T any(Class<T> clazz);
public static <T> T anyObject(); // Deprecated, use any()Usage Examples:
// Match any object
when(mock.process(any())).thenReturn("result");
verify(mock).process(any());
// Match any object of specific type
when(mock.handle(any(String.class))).thenReturn(true);
when(mock.save(any(User.class))).thenReturn(user);
// Verify with type-specific matcher
verify(userService).save(any(User.class));public static <T> T eq(T value);
public static <T> T same(T value);
public static <T> T refEq(T value, String... excludeFields);Usage Examples:
// Exact equality match
when(mock.get(eq("key"))).thenReturn("value");
verify(mock).process(eq(123));
// Same reference match
User user = new User();
when(mock.process(same(user))).thenReturn("processed");
// Reference equality with excluded fields
User expectedUser = new User("John", "john@example.com");
verify(userService).save(refEq(expectedUser, "id", "createdAt"));public static <T> T isNull();
public static <T> T isNotNull();
public static <T> T notNull(); // Deprecated, use isNotNull()Usage Examples:
// Match null values
when(service.process(isNull())).thenThrow(IllegalArgumentException.class);
// Match non-null values
when(service.process(isNotNull())).thenReturn("processed");
// Verification
verify(service).handle(isNull());
verify(service).save(isNotNull());public static String anyString();
public static String contains(String substring);
public static String matches(String regex);
public static String endsWith(String suffix);
public static String startsWith(String prefix);Usage Examples:
// Any string
when(service.process(anyString())).thenReturn("default");
// String contains substring
when(service.findByName(contains("John"))).thenReturn(users);
verify(logger).log(contains("ERROR"));
// String matches regex
when(service.validate(matches("\\d{3}-\\d{2}-\\d{4}"))).thenReturn(true);
// String starts/ends with
when(service.getByPrefix(startsWith("user_"))).thenReturn(userData);
when(service.getByExtension(endsWith(".txt"))).thenReturn(textFiles);public static byte anyByte();
public static short anyShort();
public static int anyInt();
public static long anyLong();
public static float anyFloat();
public static double anyDouble();
public static boolean anyBoolean();
public static char anyChar();Usage Examples:
// Numeric type matchers
when(calculator.add(anyInt(), anyInt())).thenReturn(42);
when(service.processRate(anyDouble())).thenReturn(true);
when(service.isActive(anyBoolean())).thenReturn("status");
// Verification
verify(calculator).multiply(anyFloat(), anyFloat());
verify(service).setAge(anyByte());public static <T> Collection<T> anyCollection();
public static <T> Collection<T> anyCollectionOf(Class<T> clazz);
public static <T> List<T> anyList();
public static <T> List<T> anyListOf(Class<T> clazz);
public static <T> Set<T> anySet();
public static <T> Set<T> anySetOf(Class<T> clazz);
public static <K, V> Map<K, V> anyMap();
public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz);Usage Examples:
// Generic collection matchers
when(service.process(anyList())).thenReturn("processed");
when(service.save(anyCollection())).thenReturn(true);
// Type-specific collection matchers
when(service.processUsers(anyListOf(User.class))).thenReturn(results);
when(service.processSettings(anyMapOf(String.class, Object.class))).thenReturn(config);
// Verification
verify(service).updateUsers(anySetOf(User.class));
verify(cache).putAll(anyMap());public class AdditionalMatchers {
public static <T> T not(T value);
public static <T> T or(T left, T right);
public static <T> T and(T left, T right);
public static <T extends Comparable<T>> T geq(T value);
public static <T extends Comparable<T>> T leq(T value);
public static <T extends Comparable<T>> T gt(T value);
public static <T extends Comparable<T>> T lt(T value);
public static <T extends Comparable<T>> T cmpEq(T value);
public static <T> T[] aryEq(T[] array);
public static String find(String regex);
}Usage Examples:
// Logical matchers
when(service.process(not(eq("invalid")))).thenReturn("valid");
when(service.handle(or(eq("a"), eq("b")))).thenReturn(true);
when(service.validate(and(startsWith("user"), endsWith("@domain.com")))).thenReturn(true);
// Comparison matchers
when(service.processAge(gt(18))).thenReturn("adult");
when(service.processScore(geq(90))).thenReturn("excellent");
when(service.processQuantity(lt(100))).thenReturn("available");
// Array equality
String[] expectedArray = {"a", "b", "c"};
verify(service).processArray(aryEq(expectedArray));
// Regex find in string
verify(logger).log(find("ERROR.*database"));public static <T> T argThat(Matcher<T> matcher);
public static boolean booleanThat(Matcher<Boolean> matcher);
public static byte byteThat(Matcher<Byte> matcher);
public static char charThat(Matcher<Character> matcher);
public static double doubleThat(Matcher<Double> matcher);
public static float floatThat(Matcher<Float> matcher);
public static int intThat(Matcher<Integer> matcher);
public static long longThat(Matcher<Long> matcher);
public static short shortThat(Matcher<Short> matcher);Usage Examples:
// Hamcrest matchers
when(service.process(argThat(hasProperty("name", equalTo("John"))))).thenReturn(user);
when(service.calculate(intThat(greaterThan(0)))).thenReturn(result);
// Custom Hamcrest matcher
verify(service).save(argThat(allOf(
hasProperty("name", notNullValue()),
hasProperty("age", greaterThan(0))
)));// Custom logic with lambda
when(service.process(argThat(user -> user.getAge() > 18))).thenReturn("adult");
// Complex validation
verify(service).save(argThat(user ->
user.getName() != null &&
user.getEmail().contains("@") &&
user.getAge() >= 18
));public interface ArgumentMatcher<T> {
boolean matches(T argument);
}Usage Example:
class IsValidEmail implements ArgumentMatcher<String> {
public boolean matches(String email) {
return email != null && email.contains("@") && email.contains(".");
}
}
// Usage
when(service.sendEmail(argThat(new IsValidEmail()))).thenReturn(true);Important Rule: If you use any matcher for one argument, you must use matchers for all arguments:
// WRONG - mixing matchers with exact values
verify(mock).someMethod(anyInt(), "exact string");
// CORRECT - use matchers for all arguments
verify(mock).someMethod(anyInt(), eq("exact string"));// Good - specific when it matters
verify(service).processUser(eq("john123"));
// Good - flexible when appropriate
verify(service).log(anyString());
// Avoid - too specific when flexibility is better
verify(service).log(eq("Processing user john123 at 2023-10-01 10:30:15"));
// Better - focus on important parts
verify(service).log(contains("Processing user john123"));// Good - simple matchers are faster
verify(service).process(anyString());
// Consider performance for complex matchers
verify(service).process(argThat(data -> {
// Complex computation here
return expensiveValidation(data);
}));// Good - clear intent
verify(emailService).sendEmail(
eq("user@example.com"),
contains("Welcome"),
any(EmailOptions.class)
);
// Avoid - unclear matchers
verify(service).process(argThat(x -> x.toString().length() > 5));
// Better - descriptive matcher
verify(service).process(argThat(hasMinimumLength(5)));// WRONG - mixing matchers and values
verify(mock).method(anyString(), "value");
// CORRECT
verify(mock).method(anyString(), eq("value"));// Potentially problematic
String nullString = null;
when(service.process(eq(nullString))).thenReturn("result");
// Better
when(service.process(isNull())).thenReturn("result");// Avoid - loses test value
verify(service).process(any(), any(), any());
// Better - be specific where it matters
verify(service).process(eq("important"), any(), anyInt());Install with Tessl CLI
npx tessl i tessl/maven-org-mockito--mockito-all