argThat
plus lambda
that is how you can fail your argument verification:
verify(mock).mymethod(argThat(
(x)->false
));
where
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
argThat
plus asserts
the above test will "say" Expected: lambda$... Was: YourClass.toSting...
. You can get a more specific cause of the failure if to use asserts in the the lambda:
verify(mock).mymethod(argThat( x -> {
assertThat(x).isNotNull();
assertThat(x.description).contains("KEY");
return true;
}));
❗️BUT❗️: THIS ONLY WORKS WHEN
- THE CALL IS EXPECTED 1 TIME, or
- the call is expected 2+ times, but all the times the verifier matches (returns
true
).
If the verified method called 2+ times, mockito passes all the called combinations to each verifier. So mockito expects your verifier silently returns true
for one of the argument set, and false
(no assert exceptions) for other valid calls. That expectation is not a problem for 1 method call - it should just return true 1 time.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
Now the failed test will say: Expected: Obj.description to contain 'KEY'. Was: 'Actual description'
. NOTE: I used assertJ
asserts, but it's up to you which assertion framework to use.
argThat
with multiple arguments.
If you use argThat
, all arguments must be provided with matches. E.g. if you had another method with 2 arguments:
verify(mock).mymethod2(eq("VALUE_1"), argThat((x)->false));
// above is correct as eq() is also an argument matcher.
verify(mock).mymethod2("VALUE_1", argThat((x)->false));
// above is incorrect; an exception will be thrown, as the first arg. is given without an argument matcher.
where:
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
eq
matcher
the easiest way to check if the argument is equal:
verify(mock).mymethod(eq(expectedValue));
// NOTE: ^ where the parentheses must be closed.
direct argument
if comparison by ref is acceptable, then go on with:
verify(mock).mymethod(expectedArg);
THE ROOT CAUSE of original question failure was the wrong place of the paranthes: verify(mock.mymethod...
. That was wrong. The right would be: verify(mock).*