Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Argument Matchers and Captors

Custom Argument Matchers with argThat

Write your own Mockito argument matchers with argThat and ArgumentMatcher lambdas, build reusable named matchers, and know when to use a captor instead.

The built-in matchers cover simple cases: any string, exactly this value, a string that starts with something. Real domain objects need richer conditions: "an order whose total is above 100", "a user whose email ends with the company domain", "a list with exactly three items". For these, Mockito lets you describe the rule yourself with argThat, which takes a function from the argument to true or false. This lesson shows how to write custom matchers, how to make them reusable and readable, and when a different tool (a captor) is the better choice.

Real Mockito code is read-only. The runnable examples use the Mini stand-in from What Is Mockito?, whose argThat(...) takes a java.util.function.Predicate. In real Mockito the argument is an ArgumentMatcher<T>, a functional interface with a single method boolean matches(T argument), so the same lambda works in both.

argThat with a lambda

Java
import static org.mockito.ArgumentMatchers.argThat;

verify(orders).save(argThat(order -> order.total() > 100 && order.customer().isVip()));

when(users.findByEmail(argThat(email -> email.endsWith("@example.com")))).thenReturn(Optional.of(staff));

The lambda receives the actual argument of each call. Mockito calls it while comparing the call against the stub or verification. Like every matcher, argThat(...) follows the matcher rules: if any argument uses a matcher, all of them must. Mix it with eq(...) for the exact ones:

Java
verify(mailer).send(eq("[email protected]"), argThat(text -> text.contains("invoice")));

For primitive parameters there are typed versions, intThat, longThat, booleanThat, doubleThat and so on, which return a safe primitive dummy value instead of null.

Try it: matching on a property of an object

Java argThat on domain objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The lambda parameters are typed ((Order o) -> ...) here so the compiler can infer the generic T of argThat when the method is overloaded or when several matchers are used.

Reusable, named matchers

A lambda is perfect for one use. When the same rule appears in many tests, or when the lambda is long enough to hide the intent of the test, put it in a small static method with a descriptive name. The method simply calls argThat and returns its result, so it can be used anywhere a matcher is allowed:

Java
static Order expressOrder() {
    return argThat(o -> o.totalCents() >= 10_000 || o.vip());
}

verify(shipping, times(2)).express(expressOrder());

Now the test reads like a sentence. If the business rule changes, you edit one method.

Failure messages

If an argThat verification fails, Mockito prints what it expected as the matcher's toString(). A lambda has no useful description, so the message just says something like argThat(...). For rules that you care about, write a small class that implements ArgumentMatcher<T> and override toString() with a readable text such as "an express order (>= 100.00 or VIP)"; that text then appears in every failure message. (Hamcrest users can reuse their matchers through MockitoHamcrest.argThat, whose description comes from Hamcrest.)

Java A named matcher helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Pitfalls

  • The lambda must not throw. A ClassCastException or NullPointerException inside argThat aborts the whole verification or stubbing. Null-check the argument if the parameter can be null, as the examples above do.
  • No side effects. Mockito may call a matcher several times (for example while looking for a matching stub), so it must be a pure yes/no function.
  • Do not hide assertions in matchers. A matcher answers yes/no; it does not tell you why an argument was rejected, which makes failures hard to read. If you need to check five properties of an argument and report each, use an ArgumentCaptor and ordinary assertions instead (ArgumentCaptor).
  • Keep it simple. If a matcher needs more than one or two conditions, ask whether the test is verifying too much of the argument.

Matcher or captor?

Use argThat when... Use a captor when...
A short yes/no rule decides which call matches (a filter) You want to look at the argument afterwards with several assertions (an inspection)
The rule is reused in stubbing and verification The argument is built inside the code under test and has many fields to check
You only need pass or fail You want precise assertion messages from assertEquals

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does argThat take?

    argThat takes an ArgumentMatcher (a lambda from the argument to boolean) which Mockito calls with the actual argument.
  2. 2. You use argThat for the first parameter of a two-parameter method. What must the second parameter be?

    All-or-none: once one argument uses a matcher, all arguments must.
  3. 3. Why should the lambda in argThat be free of side effects and not throw?

    A matcher is a pure yes/no function that Mockito can call repeatedly while searching for matching calls.
  4. 4. When is an ArgumentCaptor better than argThat?

    A captor hands you the argument so you can assert on each field with clear messages; argThat only answers yes or no.

Summary

  • argThat(lambda) lets you write your own match rule; typed variants such as intThat exist for primitives.
  • All-or-none still applies: combine with eq(...) for exact arguments.
  • Wrap repeated rules in named static helper methods; use a small ArgumentMatcher class with toString() for readable failure messages.
  • Keep matchers pure, null-safe and small; use captors when you need to inspect an argument in detail.

Next: ArgumentCaptor