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

additional-matchers.mddocs/

Additional Argument Matchers

This section covers advanced argument matchers for complex matching scenarios, including numerical comparisons, logical combinations, array equality, and specialized string matching.

Numerical Comparison Matchers

Greater Than or Equal (geq)

Match arguments greater than or equal to a specified value.

public static <T extends Comparable<T>> T geq(T value)
public static byte geq(byte value)
public static double geq(double value)
public static float geq(float value)
public static int geq(int value)
public static long geq(long value)
public static short geq(short value)

Usage Examples:

NumberService mockService = mock(NumberService.class);

// Stub methods with geq matchers
when(mockService.processScore(geq(85))).thenReturn("Grade A");
when(mockService.processAge(geq((byte) 18))).thenReturn("Adult");
when(mockService.processDouble(geq(3.14))).thenReturn("Pi or greater");

// Use the mock
mockService.processScore(90);     // Returns "Grade A"
mockService.processScore(85);     // Returns "Grade A"  
mockService.processScore(80);     // No match, returns default

// Verify with geq matcher
verify(mockService).processScore(geq(85));
verify(mockService).processAge(geq((byte) 18));

Less Than or Equal (leq)

Match arguments less than or equal to a specified value.

public static <T extends Comparable<T>> T leq(T value)
public static byte leq(byte value)
public static double leq(double value)
public static float leq(float value)
public static int leq(int value)
public static long leq(long value)
public static short leq(short value)

Usage Examples:

ValidationService mockService = mock(ValidationService.class);

// Stub with leq matchers
when(mockService.checkLimit(leq(100))).thenReturn(true);
when(mockService.validatePrice(leq(99.99f))).thenReturn("Affordable");
when(mockService.checkBuffer(leq(1024L))).thenReturn("Within limit");

// Use the mock
mockService.checkLimit(75);        // Returns true
mockService.checkLimit(100);       // Returns true
mockService.checkLimit(150);       // No match

// Verify with leq matcher
verify(mockService).checkLimit(leq(100));
verify(mockService).validatePrice(leq(99.99f));

Greater Than (gt)

Match arguments strictly greater than a specified value.

public static <T extends Comparable<T>> T gt(T value)
public static byte gt(byte value)
public static double gt(double value)
public static float gt(float value)
public static int gt(int value)
public static long gt(long value)
public static short gt(short value)

Usage Examples:

ScoreService mockService = mock(ScoreService.class);

// Stub with gt matchers
when(mockService.evaluateScore(gt(90))).thenReturn("Excellent");
when(mockService.checkTemperature(gt(100.0))).thenReturn("Boiling");
when(mockService.validateCount(gt((short) 0))).thenReturn("Positive");

// Use the mock
mockService.evaluateScore(95);     // Returns "Excellent"
mockService.evaluateScore(90);     // No match (not greater than 90)
mockService.evaluateScore(85);     // No match

// Verify with gt matcher
verify(mockService).evaluateScore(gt(90));
verify(mockService).checkTemperature(gt(100.0));

Less Than (lt)

Match arguments strictly less than a specified value.

public static <T extends Comparable<T>> T lt(T value)
public static byte lt(byte value)
public static double lt(double value)
public static float lt(float value)
public static int lt(int value)
public static long lt(long value)
public static short lt(short value)

Usage Examples:

RangeService mockService = mock(RangeService.class);

// Stub with lt matchers
when(mockService.processSmallNumbers(lt(10))).thenReturn("Single digit");
when(mockService.checkPrecision(lt(0.001))).thenReturn("High precision");
when(mockService.validateThreshold(lt(500L))).thenReturn("Below threshold");

// Use the mock
mockService.processSmallNumbers(5);    // Returns "Single digit"
mockService.processSmallNumbers(10);   // No match (not less than 10)
mockService.processSmallNumbers(15);   // No match

// Verify with lt matcher
verify(mockService).processSmallNumbers(lt(10));
verify(mockService).checkPrecision(lt(0.001));

Comparison-Based Matchers

Comparable Equality (cmpEq)

Match arguments equal according to their compareTo method rather than equals.

public static <T extends Comparable<T>> T cmpEq(T value)

Usage Examples:

DateService mockService = mock(DateService.class);

// Create dates that are compareTo equal but not equals
Date date1 = new Date(1000);
Date date2 = new Date(1000);

// Stub with cmpEq matcher
when(mockService.processDate(cmpEq(date1))).thenReturn("Processed");

// Use the mock
mockService.processDate(date2);   // Matches via compareTo

// Verify with cmpEq matcher
verify(mockService).processDate(cmpEq(date1));

// Works with other Comparable types
BigDecimal decimal = new BigDecimal("10.00");
when(mockService.processDecimal(cmpEq(decimal))).thenReturn("Valid");

// Matches BigDecimal("10.0") via compareTo
mockService.processDecimal(new BigDecimal("10.0"));

String Pattern Matchers

Regular Expression Matching (find)

Match string arguments that contain a substring matching a regular expression.

public static String find(String regex)

Usage Examples:

TextService mockService = mock(TextService.class);

// Stub with regex pattern matchers
when(mockService.validateEmail(find("@[a-zA-Z0-9.-]+\\."))).thenReturn(true);
when(mockService.parsePhoneNumber(find("\\d{3}-\\d{3}-\\d{4}"))).thenReturn("Valid format");
when(mockService.extractNumbers(find("\\d+"))).thenReturn("Contains digits");

// Use the mock
mockService.validateEmail("user@example.com");           // Matches email pattern
mockService.parsePhoneNumber("Call me at 555-123-4567"); // Matches phone pattern
mockService.extractNumbers("Room 101");                  // Contains digits

// Verify with find matcher
verify(mockService).validateEmail(find("@[a-zA-Z0-9.-]+\\."));
verify(mockService).parsePhoneNumber(find("\\d{3}-\\d{3}-\\d{4}"));

// Complex patterns
when(mockService.validateCode(find("^[A-Z]{2}\\d{4}$"))).thenReturn("Valid code");
mockService.validateCode("AB1234");  // Matches exact pattern

Array Equality Matchers

Object Array Equality (aryEq)

Match array arguments using deep equality comparison.

public static <T> T[] aryEq(T[] value)
public static boolean[] aryEq(boolean[] value)
public static byte[] aryEq(byte[] value)
public static char[] aryEq(char[] value)
public static double[] aryEq(double[] value)
public static float[] aryEq(float[] value)
public static int[] aryEq(int[] value)
public static long[] aryEq(long[] value)
public static short[] aryEq(short[] value)

Usage Examples:

ArrayService mockService = mock(ArrayService.class);

// Object array matching
String[] expectedStrings = {"hello", "world"};
when(mockService.processStrings(aryEq(expectedStrings))).thenReturn("Processed");

String[] actualStrings = {"hello", "world"};
mockService.processStrings(actualStrings);  // Matches via array equality

// Primitive array matching
int[] expectedNumbers = {1, 2, 3, 4, 5};
when(mockService.processNumbers(aryEq(expectedNumbers))).thenReturn(15);

int[] actualNumbers = {1, 2, 3, 4, 5};
mockService.processNumbers(actualNumbers);  // Matches

// Other primitive types
double[] expectedDoubles = {1.1, 2.2, 3.3};
when(mockService.processDoubles(aryEq(expectedDoubles))).thenReturn("Calculated");

boolean[] expectedFlags = {true, false, true};
when(mockService.processFlags(aryEq(expectedFlags))).thenReturn("Flags processed");

// Verify with array equality
verify(mockService).processStrings(aryEq(expectedStrings));
verify(mockService).processNumbers(aryEq(expectedNumbers));

Logical Combination Matchers

Logical AND (and)

Match arguments that satisfy both of two matchers.

public static <T> T and(T first, T second)
public static boolean and(boolean first, boolean second)
public static byte and(byte first, byte second)
public static char and(char first, char second)
public static double and(double first, double second)
public static float and(float first, float second)
public static int and(int first, int second)
public static long and(long first, long second)
public static short and(short first, short second)

Usage Examples:

RangeService mockService = mock(RangeService.class);

// Combine numeric matchers with AND
when(mockService.processInRange(and(gt(10), lt(100)))).thenReturn("In range");
when(mockService.validateScore(and(geq(0), leq(100)))).thenReturn("Valid score");

// Use the mock
mockService.processInRange(50);    // Matches: 50 > 10 AND 50 < 100
mockService.processInRange(5);     // No match: 5 not > 10
mockService.processInRange(150);   // No match: 150 not < 100

// Combine string matchers
when(mockService.validateInput(and(startsWith("user_"), endsWith(".txt"))))
    .thenReturn("Valid filename");

mockService.validateInput("user_data.txt");  // Matches both conditions
mockService.validateInput("user_data.pdf");  // No match (wrong extension)

// Verify with AND combinations
verify(mockService).processInRange(and(gt(10), lt(100)));
verify(mockService).validateScore(and(geq(0), leq(100)));

Logical OR (or)

Match arguments that satisfy either of two matchers.

public static <T> T or(T first, T second)
public static boolean or(boolean first, boolean second)
public static byte or(byte first, byte second)
public static char or(char first, char second)
public static double or(double first, double second)
public static float or(float first, float second)
public static int or(int first, int second)
public static long or(long first, long second)
public static short or(short first, short short)

Usage Examples:

ValidationService mockService = mock(ValidationService.class);

// Combine conditions with OR
when(mockService.isSpecialNumber(or(eq(0), eq(1)))).thenReturn("Binary digit");
when(mockService.isExtreme(or(lt(10), gt(90)))).thenReturn("Extreme value");

// Use the mock
mockService.isSpecialNumber(0);    // Matches: equals 0
mockService.isSpecialNumber(1);    // Matches: equals 1
mockService.isSpecialNumber(5);    // No match

mockService.isExtreme(5);          // Matches: 5 < 10
mockService.isExtreme(95);         // Matches: 95 > 90
mockService.isExtreme(50);         // No match

// String combinations
when(mockService.isValidExtension(or(endsWith(".jpg"), endsWith(".png"))))
    .thenReturn("Valid image");

mockService.isValidExtension("photo.jpg");  // Matches
mockService.isValidExtension("image.png");  // Matches
mockService.isValidExtension("doc.txt");    // No match

// Verify with OR combinations
verify(mockService).isSpecialNumber(or(eq(0), eq(1)));
verify(mockService).isExtreme(or(lt(10), gt(90)));

Logical NOT (not)

Match arguments that do NOT satisfy the given matcher.

public static <T> T not(T matcher)
public static boolean not(boolean matcher)
public static byte not(byte matcher)
public static char not(char matcher)
public static double not(double matcher)
public static float not(float matcher)
public static int not(int matcher)
public static long not(long matcher)
public static short not(short matcher)

Usage Examples:

FilterService mockService = mock(FilterService.class);

// Negate matchers with NOT
when(mockService.processNonZero(not(eq(0)))).thenReturn("Non-zero");
when(mockService.excludeRange(not(and(geq(10), leq(20))))).thenReturn("Outside range");

// Use the mock
mockService.processNonZero(5);     // Matches: 5 is not equal to 0
mockService.processNonZero(0);     // No match: 0 equals 0

mockService.excludeRange(5);       // Matches: 5 is not in range [10,20]
mockService.excludeRange(15);      // No match: 15 is in range [10,20]

// String negation
when(mockService.processNonEmpty(not(eq("")))).thenReturn("Has content");
when(mockService.filterFiles(not(endsWith(".tmp")))).thenReturn("Permanent file");

mockService.processNonEmpty("hello");    // Matches: not empty
mockService.processNonEmpty("");         // No match: is empty

mockService.filterFiles("data.txt");     // Matches: not .tmp
mockService.filterFiles("temp.tmp");     // No match: is .tmp

// Verify with NOT
verify(mockService).processNonZero(not(eq(0)));
verify(mockService).excludeRange(not(and(geq(10), leq(20))));

Floating-Point Equality with Delta

Delta-Based Equality (eq)

Match floating-point numbers within a specified tolerance.

public static double eq(double value, double delta)
public static float eq(float value, float delta)

Usage Examples:

MathService mockService = mock(MathService.class);

// Floating-point equality with tolerance
when(mockService.processApproximateDouble(eq(3.14159, 0.001))).thenReturn("Pi");
when(mockService.validateFloat(eq(2.5f, 0.1f))).thenReturn("Close enough");

// Use the mock
mockService.processApproximateDouble(3.141);   // Matches: within 0.001 of pi
mockService.processApproximateDouble(3.142);   // Matches: within 0.001 of pi
mockService.processApproximateDouble(3.15);    // No match: difference > 0.001

mockService.validateFloat(2.45f);              // Matches: within 0.1 of 2.5
mockService.validateFloat(2.55f);              // Matches: within 0.1 of 2.5
mockService.validateFloat(2.7f);               // No match: difference > 0.1

// Common use case: comparing calculated results
double expected = calculateExpectedResult();
when(mockService.verifyCalculation(eq(expected, 0.0001)))
    .thenReturn("Calculation correct");

// Verify with delta equality
verify(mockService).processApproximateDouble(eq(3.14159, 0.001));
verify(mockService).validateFloat(eq(2.5f, 0.1f));

Complex Matcher Combinations

Advanced Pattern Matching

Combine multiple additional matchers for sophisticated argument validation.

Usage Examples:

ComplexService mockService = mock(ComplexService.class);

// Complex numeric range validation
when(mockService.processComplexRange(
    and(
        or(lt(0), gt(100)), 
        not(eq(-1))
    )
)).thenReturn("Complex condition met");

// This matches numbers that are:
// - (Less than 0 OR greater than 100) AND not equal to -1
mockService.processComplexRange(-5);   // Matches: < 0 and != -1
mockService.processComplexRange(150);  // Matches: > 100 and != -1  
mockService.processComplexRange(-1);   // No match: equals -1
mockService.processComplexRange(50);   // No match: not < 0 and not > 100

// Combining string and array matchers
String[] validFormats = {"json", "xml", "csv"};
when(mockService.processData(
    find("\\.(json|xml|csv)$"),
    aryEq(validFormats)
)).thenReturn("Valid data processing");

// Array validation with numerical constraints
int[] expectedSizes = {1, 5, 10, 50};
when(mockService.validateSizes(
    aryEq(expectedSizes),
    geq(4)
)).thenReturn("Size validation passed");

Import Statement

To use AdditionalMatchers, include this import in your test files:

import static org.mockito.AdditionalMatchers.*;

This static import provides access to all additional matcher methods including geq, leq, gt, lt, cmpEq, find, aryEq, and, or, not, and eq with delta.

Best Practices

When to Use Additional Matchers

  • Numerical Ranges: Use gt, geq, lt, leq for validating numeric boundaries
  • Array Comparisons: Use aryEq when you need deep equality checking for arrays
  • Complex Logic: Use and, or, not to create sophisticated matching conditions
  • String Patterns: Use find for regex-based string validation
  • Floating-Point: Use eq with delta for comparing calculated floating-point results

Performance Considerations

Additional matchers may have performance implications in tests with many mock interactions. Consider the complexity of your matching logic and prefer simpler matchers when possible.

Readability Guidelines

While additional matchers are powerful, they can make tests harder to read. Use them judiciously and consider extracting complex matcher combinations into well-named variables:

// Good: Clear and readable
ArgumentMatcher<Integer> validScore = and(geq(0), leq(100));
when(mockService.validateScore(argThat(validScore))).thenReturn(true);

// Also good: Inline when simple
when(mockService.processPositive(gt(0))).thenReturn("positive");

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