I'm running into a generics problem with Mockito and Hamcrest.
Please assume the following interface:
public interface Service {
void perform(Collection<String> elements);
}
And the following test snippet:
Service service = mock(Service.class);
// ... perform business logic
verify(service).perform(Matchers.argThat(contains("a", "b")));
So I want to verify that my business logic actually called the service with a collection that contains "a" and "b" in that order.
However, the return type of contains(...)
is Matcher<Iterable<? extends E>>
, so Matchers.argThat(...)
returns Iterable<String>
in my case, which naturally does not apply to the required Collection<String>
.
I know that I could use an argument captor as proposed in Hamcrest hasItem and Mockito verify inconsistency, but I would very much like not to.
Any suggestions! Thanks!
Matcher<Iterable<String>>
toMatcher<Collection<String>>
? That surely won't compile... – Halliardequals
implementation then you can callverify
with collection instance that contains 'a' and 'b'. But this would be bad test - first you will explode implementation details as well you have to relay on correct equals method. So I would use argument captor without doubts – ElataIsListOfTwoElements
here: docs.mockito.googlecode.com/hg/org/mockito/ArgumentMatcher.html – Moleskinverify(service).perform((Collection<String>) Matchers.argThat(contains("a", "b")));
? – NolascoCollection
sinceCollection
is not guaranteed to be an ordered collection. Are you sure you meant Collection and notList
? – DorisoncontainsInAnyOrder
then, which has the same signature. – Halliard