Contents

Custom Argument Matching in Mockito with argThat() and Java Lambdas

Updated on 2026-10-21

Introduction

With version 2.1.0, Mockito introduced the lambda matcher to verify the input of method calls. Before this update, we only had ArgumentCaptor to verify the input.

Lambda matcher

With argThat, we create a matcher that is validated against the input of each method invocation. In the example below, we create this matcher argThat(a -> a.contains("o")) that verifies that every added word contains the letter “o”. the Lambda matcher is especially useful for less complex test cases.

You could use an ArgumentCaptor instance to verify a mocked method's input. But that results in multiple lines of code that you need to maintain. While it could be worth it if you do a lot of assertions.

1
2
3
4
5
6
7
@Test
void simpleArgumentMatchers() {
    List<String> list = (List<String>) mock(List.class);
    list.add("one");
    list.add("two");
    verify(list, times(2)).add(argThat(a -> a.contains("o")));
}

Multiple Lambda matchers

If we mock a method with multiple arguments, we need to add an argThat for each argument you pass to the method, like in the example below, the put method has two inputs.

1
2
3
4
5
6
7
@Test
void simpleArgumentMatchersMultipleArguments() {
    Map<String, Integer> map = (Map<String,Integer>) mock(Map.class);
    map.put("one", 1);
    map.put("two", 2);
    verify(map, times(2)).put(argThat(a -> a.contains("o") ),argThat(a -> a < 3 ));
}

Conclusion

This post took a quick look at how to use Mockito's lambda matchers. We saw two examples with different amounts of input parameters. The Lambda matcher is especially useful for less complex test cases. The ArgumentCaptor is better suited for more complex cases with multiple assertions.

Further reading

More about testing in Java:

✅ In-House Team Workshop · 1 Day (Live In-Person On-Site)

Level Up Your Team's Java Testing: JUnit 5, Mockito & Testcontainers

Slow, flaky, or brittle test suites kill developer velocity. In my 1-day Modern Testing in Java Workshop, your team learns how to design fast, maintainable unit and microservice integration tests using advanced JUnit 5, Mockito, and Testcontainers on your real codebase.

Stay Connected · Code, Benchmarks & Talks

Want More Deep-Dive JVM Benchmarks & Project Panama Research?

Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides:

David Vlijmincx
David Vlijmincx

Senior Java Performance & Concurrency Engineer with 10+ years of production JVM experience. International speaker with 35+ talks at Devoxx, P99 CONF, JFokus, JavaZone, and Devnexus, creator of JUring (Linux io_uring for Java), and enterprise Java workshop trainer.