Mockito and Hamcrest: how to verify invocation of Collection argument?

Viewed 62615

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!

7 Answers

You can put your own lambda as an ArgumentMatcher

when(myClass.myMethod(argThat(arg -> arg.containsAll(asList(1,2))))
    .thenReturn(...);

Similar to another answer here you can do the following:

verify(yourmock, times(1)).yourmethod(argThat(arg -> arg.containsAll(asList("a", "b"))));
Related