Say I am mocking this class Foo
class Foo {
public void doThing(Bar bar) {
// ...
}
}
and this is Bar
class Bar {
private int i;
public int getI() { return i; }
public void setI(int i) { this.i = i; }
}
I know I can use Mockito's verify functionality to see if Foo#doThing(Bar)
was called on the mock with a specific instance of Bar
or any Bar
with Mockito.any(Bar.class)
, but is there some way to ensure it was called by any Bar
but with a specific value for i
or Bar#getI()
?
What I know is possible:
Foo mockedFoo = mock(Foo.class);
Bar someBar = mock(Bar.class);
...
verify(mockedFoo).doThing(someBar);
verify(mockedFoo).doThing(any(Bar.class);
What I want to know is if there is a way to verify that a Bar
with particular things true about it was passed as an argument.
In Mockito 2.1.0 and up with Java 8 you can pass the lambda to argThat out of the box so that one does not need a custom argument matchers. For the example in the OP would be:
verify(mockedFoo).doThing(argThat((Bar aBar) -> aBar.getI() == 5));
This is because as of Mockito 2.1.0, ArgumentMatcher
is a functional interface.