Contents

Mockito lambda matcher

Written by: David Vlijmincx

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: