CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-mockito--mockito-core

Mockito mock objects library core API and implementation for comprehensive Java unit testing

Pending
Overview
Eval results
Files

argument-matching.mddocs/

Argument Matching

This section covers flexible argument matching for stubbing and verification, including built-in matchers, custom matchers, and advanced matching patterns.

Key Points:

  • Since Mockito 2.1.0, type matchers exclude null values - use isNull() to match nulls explicitly
  • Since Mockito 5.0.0, any() no longer matches varargs - use any(Class) instead
  • When using argument matchers, all arguments must be provided by matchers (or wrapped with eq())
  • Use primitive-specific matchers (intThat(), booleanThat(), etc.) to avoid NullPointerException from auto-unboxing

Basic Argument Matchers

Common Type Matchers

Match arguments by type without specifying exact values.

Important Notes:

  • Since Mockito 2.1.0, type matchers like any(Class) and primitive matchers exclude null values
  • Since Mockito 5.0.0, any() no longer matches varargs - use any(Class) instead
  • For matching null values, use isNull() explicitly
public static <T> T any()
public static <T> T any(Class<T> type)
public static String anyString()
public static int anyInt() 
public static long anyLong()
public static double anyDouble()
public static float anyFloat()
public static boolean anyBoolean()
public static byte anyByte()
public static short anyShort()
public static char anyChar()

Usage Examples:

List<String> mockList = mock(List.class);

// Stub with type matchers
when(mockList.get(anyInt())).thenReturn("any element");
when(mockList.add(anyString())).thenReturn(true);

// Use mock
mockList.add("hello");
mockList.get(5);

// Verify with type matchers
verify(mockList).add(anyString());
verify(mockList).get(anyInt());

Collection Matchers

Match collections and iterables with flexible patterns.

Note: Since Mockito 2.1.0, these matchers only accept non-null instances. Use isNull() to explicitly match null values.

public static <T> Collection<T> anyCollection()
public static <T> List<T> anyList()
public static <T> Set<T> anySet()
public static <K, V> Map<K, V> anyMap()
public static <T> Iterable<T> anyIterable()

Usage Examples:

DataService mockService = mock(DataService.class);

// Stub with collection matchers
when(mockService.processItems(anyList())).thenReturn("processed");
when(mockService.processMap(anyMap()))
    .thenReturn("map processed");
when(mockService.processIterable(anyIterable())).thenReturn("iterable processed");

// Use mock
mockService.processItems(Arrays.asList("a", "b", "c"));
mockService.processMap(Map.of("key", 123));
mockService.processIterable(Set.of("x", "y", "z"));

// Verify with collection matchers
verify(mockService).processItems(anyList());
verify(mockService).processMap(anyMap());
verify(mockService).processIterable(anyIterable());

Exact Value Matchers

Equality and Null Matchers

Match specific values or null/non-null conditions.

// Equality matchers for all types
public static <T> T eq(T value)
public static boolean eq(boolean value)
public static byte eq(byte value)
public static char eq(char value)
public static double eq(double value)
public static float eq(float value)
public static int eq(int value)
public static long eq(long value)
public static short eq(short value)

// Advanced equality matchers
public static <T> T refEq(T value, String... excludeFields)
public static <T> T same(T value)

// Null/not-null matchers
public static <T> T isNull()
public static <T> T isNull(Class<T> type)
public static <T> T isNotNull()
public static <T> T isNotNull(Class<T> type)
public static <T> T notNull()
public static <T> T notNull(Class<T> type)

// Type and nullability matchers
public static <T> T isA(Class<T> type)
public static <T> T nullable(Class<T> clazz)

Usage Examples:

UserService mockService = mock(UserService.class);

// Exact value matching
when(mockService.findUser(eq("john"))).thenReturn(johnUser);
when(mockService.findUser(eq("jane"))).thenReturn(janeUser);

// Null matchers
when(mockService.findUser(isNull())).thenThrow(IllegalArgumentException.class);
when(mockService.findUser(isNull(String.class))).thenThrow(IllegalArgumentException.class);
when(mockService.createUser(notNull())).thenReturn(true);
when(mockService.createUser(notNull(User.class))).thenReturn(true);

// Nullable matcher (accepts null or specified type)
when(mockService.processUser(nullable(User.class))).thenReturn("processed");

// Type checking
when(mockService.process(isA(AdminUser.class))).thenReturn("admin");

// Reference equality
User specificUser = new User("test");
when(mockService.updateUser(same(specificUser))).thenReturn(true);

// Reflection equality (ignoring specific fields)
User template = new User("john", "john@example.com");
when(mockService.createUser(refEq(template, "id", "createdAt")))
    .thenReturn(true);

String Matchers

String Pattern Matching

Match strings with patterns and conditions.

public static String startsWith(String prefix)
public static String endsWith(String suffix)
public static String contains(String substring)
public static String matches(String regex)
public static String matches(Pattern pattern)

Usage Examples:

EmailService mockService = mock(EmailService.class);

// String pattern matching
when(mockService.sendEmail(startsWith("urgent:"))).thenReturn(true);
when(mockService.sendEmail(endsWith("@company.com"))).thenReturn(true);
when(mockService.sendEmail(contains("password"))).thenReturn(false);

// Regex matching
when(mockService.validateEmail(matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")))
    .thenReturn(true);

// Pattern matching
Pattern emailPattern = Pattern.compile(".*@.*\\.com");
when(mockService.validateEmail(matches(emailPattern))).thenReturn(true);

// Verify with string matchers
verify(mockService).sendEmail(startsWith("urgent:"));
verify(mockService).validateEmail(matches(".*@.*"));

Custom Argument Matchers

ArgumentMatcher Interface

Create custom matching logic for complex scenarios.

public static <T> T argThat(ArgumentMatcher<T> matcher)
public static <T> T assertArg(Consumer<T> consumer)
public static <T> T assertArg(ThrowingConsumer<T> consumer)

// Primitive-specific matchers to avoid NullPointerException
public static boolean booleanThat(ArgumentMatcher<Boolean> matcher)
public static byte byteThat(ArgumentMatcher<Byte> matcher)
public static char charThat(ArgumentMatcher<Character> matcher)
public static short shortThat(ArgumentMatcher<Short> matcher)
public static int intThat(ArgumentMatcher<Integer> matcher)
public static long longThat(ArgumentMatcher<Long> matcher)
public static float floatThat(ArgumentMatcher<Float> matcher)
public static double doubleThat(ArgumentMatcher<Double> matcher)

interface ArgumentMatcher<T> {
    boolean matches(T argument);
    default String toString() {
        return "custom matcher";
    }
}

Usage Examples:

List<String> mockList = mock(List.class);

// Custom matcher using lambda
when(mockList.add(argThat(s -> s.length() > 5))).thenReturn(true);

// Custom matcher with description
ArgumentMatcher<String> longString = new ArgumentMatcher<String>() {
    @Override
    public boolean matches(String argument) {
        return argument != null && argument.length() > 10;
    }
    
    @Override  
    public String toString() {
        return "string longer than 10 characters";
    }
};

when(mockList.add(argThat(longString))).thenReturn(true);

// Using method reference
when(mockList.add(argThat(String::isEmpty))).thenReturn(false);

// Complex object matching
User expectedUser = new User("john", "john@example.com");
when(userService.createUser(argThat(user -> 
    user.getName().equals("john") && 
    user.getEmail().contains("@") &&
    user.getAge() >= 18
))).thenReturn(true);

AdditionalMatchers Utility

Additional matchers for numeric and array comparisons.

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> T[] aryEq(T[] value)
public static <T> T and(T first, T second)
public static <T> T or(T first, T second)
public static <T> T not(T matcher)

Usage Examples:

NumberService mockService = mock(NumberService.class);

// Numeric comparisons
when(mockService.process(gt(100))).thenReturn("large");
when(mockService.process(lt(10))).thenReturn("small");
when(mockService.process(geq(50))).thenReturn("medium+");

// Array equality
int[] expectedArray = {1, 2, 3};
when(mockService.processArray(aryEq(expectedArray))).thenReturn(true);

// Logical combinations
when(mockService.process(and(gt(10), lt(100)))).thenReturn("medium");
when(mockService.process(or(eq(0), eq(1)))).thenReturn("binary");
when(mockService.process(not(eq(42)))).thenReturn("not answer");

Advanced Matching Patterns

Capturing Arguments with Matchers

Combine argument capturing with flexible matching.

public static <T> T assertArg(Consumer<T> assertion)

Usage Examples:

UserService mockService = mock(UserService.class);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);

// Use mock
User newUser = new User("alice", "alice@example.com");
mockService.createUser(newUser);

// Capture and assert
verify(mockService).createUser(userCaptor.capture());
User capturedUser = userCaptor.getValue();
assertEquals("alice", capturedUser.getName());
assertTrue(capturedUser.getEmail().contains("@"));

// Using assertArg - more direct approach for assertions
verify(mockService).createUser(assertArg(user -> {
    assertEquals("alice", user.getName());
    assertTrue(user.getEmail().contains("@"));
    assertNotNull(user.getId());
}));

// Using assertArg with ThrowingConsumer for checked exceptions
verify(fileService).processFile(assertArg(file -> {
    assertTrue(file.exists());
    assertTrue(file.canRead());
    // Can throw IOException here
}));

// Primitive-specific matchers to avoid NullPointerException on auto-unboxing
when(calculator.calculate(intThat(x -> x > 0))).thenReturn("positive");
when(validator.isValid(booleanThat(b -> b == true))).thenReturn("confirmed");
when(processor.process(doubleThat(d -> d >= 0.0 && d <= 1.0))).thenReturn("normalized");

Matcher Combination Strategies

Complex matching patterns using multiple matchers.

Usage Examples:

SearchService mockService = mock(SearchService.class);

// Combining multiple conditions
when(mockService.search(
    argThat(query -> query.length() > 3),
    argThat(filters -> filters.containsKey("category")),
    anyInt()
)).thenReturn(searchResults);

// Mixed exact and flexible matching
when(mockService.searchUsers(
    eq("active"),
    argThat(age -> age >= 18 && age <= 65),
    anyString(),
    isNotNull()
)).thenReturn(activeAdults);

// Nested object matching
when(mockService.processRequest(argThat(request -> 
    request.getUser() != null &&
    request.getUser().isActive() &&
    request.getParameters().size() > 0
))).thenReturn(successResponse);

Common Matching Pitfalls

Matcher Mixing Rules

Understanding when and how to mix matchers with exact values.

Incorrect Usage:

// DON'T MIX matchers and exact values
when(mockList.subList(anyInt(), 10)).thenReturn(sublist); // WRONG!

Correct Usage:

// Use matchers for all arguments or none
when(mockList.subList(anyInt(), anyInt())).thenReturn(sublist); // CORRECT
when(mockList.subList(0, 10)).thenReturn(sublist); // ALSO CORRECT

// Or use eq() to make exact values explicit
when(mockList.subList(anyInt(), eq(10))).thenReturn(sublist); // CORRECT

Null Handling in Matchers

Proper handling of null values in custom matchers.

// Null-safe custom matcher
ArgumentMatcher<String> safeStringMatcher = s -> 
    s != null && s.trim().length() > 0;

// Or more explicit
ArgumentMatcher<User> activeUserMatcher = user -> {
    if (user == null) return false;
    return user.isActive() && user.getName() != null;
};

// Use nullable() matcher when null OR a specific type is acceptable
when(userService.findUser(nullable(String.class))).thenReturn(defaultUser);
// This matches both null and any non-null String

Install with Tessl CLI

npx tessl i tessl/maven-org-mockito--mockito-core

docs

additional-answers.md

additional-matchers.md

advanced-features.md

annotations.md

argument-matching.md

bdd-testing.md

index.md

mock-creation.md

static-mocking.md

stubbing.md

verification.md

tile.json