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.
|
|
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.
|
|
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: