Reputation: 16490
I am testing a method that returns no results. The last step of the method is something like:
insertIntoDb(someObjectContainingAListField);
I could do
verify(xx).insertIntoDb(eq(someObjectContainingAListField));
But that would verify the entire object contents; I only need to verify the list.
I really only want to verify that the List it contains is correct.
Is there any way to do so in Mockito?
Upvotes: 0
Views: 3486
Reputation: 95644
You have two main choices: Use an ArgumentCaptor, or write an ArgumentMatcher.
ArgumentCaptor lets you get a reference to the object as part of your verification, so then you can make specific assertions about it. You can create them manually with ArgumentCaptor.forClass, or use the @Captor annotation with MockitoAnnotations or the Mockito Runner or Rule.
@Captor ArgumentCaptor<ListFieldContainer> listFieldContainerCaptor;
@Test public void yourTest() {
yourClass.doSomething();
verify(mockService).insertIntoDb(listFieldContainerCaptor.capture());
ListFieldContainer listFieldContainer = listFieldContainerCaptor.getValue();
assertEquals(3, listFieldContainer.getListField().size());
}
Using a Mockito ArgumentMatcher or a Hamcrest Matcher, you can create an object that represents the predicate you're looking for.
@Test public void yourTest() {
yourClass.doSomething();
verify(mockService).insertIntoDb(argThat(
new ArgumentMatcher<ListFieldContainer>() {
@Override public boolean matches(ListFieldContainer container) {
return (container.size() == 3);
}
});
}
Note that previous versions of Mockito relied directly on Hamcrest, such that Matchers.argThat took a Hamcrest matcher; newer versions of Mockito use ArgumentMatchers.argThat to take a Hamcrest-like ArgumentMatcher interface and MockitoHamcrest.argThat to adapt a proper Hamcrest matcher.
See also: Mockito - how to mock/verify a method call which accepts a new object?
Upvotes: 2