Reputation: 4173
How can I mock a method call with Mockito with an integer argument value greater then X?
I would like to write something like this:
doReturn("FooBar").when(persons).getPersons(Mockito.gt(10));
Upvotes: 5
Views: 9828
Reputation: 101
Use AdditionalMatchers.gt:
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.AdditionalMatchers.gt;
...
@Mock
private WalletService walletService;
...
@Before...
when(walletService.withdraw(eq(777), gt(1000),
eq("USD"))).thenReturn(INSUFFICIENT_FUNDS);
...
@Test...
Upvotes: 6
Reputation: 5491
Mockito 2
Hamcrest is no longer a dependency to Mockito matchers.
However, I found MockitoHamcrest
which seems to provide interoperability with Hamcrest matchers. Applied to the example in question, it would look like this:
doReturn("FooBar").when(persons)
.getPersons(MockitoHamcrest.intThat(Matchers.greaterThan(10)));
Upvotes: 7
Reputation: 4173
Mockito uses the matchers of Hamcrest. All of Mockitos argument matchers use these matchers to match the provided argument in a handy and type-safe way.
Mockito provides also the method argThat(Matcher)
to use any matcher implementation of Hamcrest or custom Matcher
implementation. There are also specialised versions as intThat(Matcher)
for all primitved types.
So, knowing that, I rewrote the mocking of the method call:
doReturn("FooBar")
.when(persons)
.getPersons(Mockito.intThat(Matchers.greaterThan(10));
Upvotes: 12
Reputation: 691715
Write a Hamcrest Matcher<Integer>
by extending ArgumentMatcher (named IntGreaterThan, for example), and then use
doReturn("FooBar").when(persons).getPersons(intThat(MyMatchers.isGreatherThan(10)));
where MyMatchers.isGreaterThan(10)
creates a new instance of your IntGreatherThan matcher.
If you static import MyMatchers.isGreaterThan
, it becomes
doReturn("FooBar").when(persons).getPersons(intThat(isGreatherThan(10)));
Upvotes: 1