Mockito: Verifying with generic parameters

JavaGenericsParametersVerificationMockito

Java Problem Overview


With Mockito I can do the following:

verify(someService).process(any(Person.class));

But how do I write this if process takes a Collection<Person> instead? Can't figure out how to write it correctly. Just getting syntax errors...

Java Solutions


Solution 1 - Java

Try:

verify(someService).process(Matchers.<Collection<Person>>any());

Actually, IntelliJ automatically suggested this fix when I typed any()... Unfortunately you cannot use static import in this case.

Solution 2 - Java

Try :

verify(someService).process(anyCollectionOf(Person.class));

Since version 1.8 Mockito introduces

public static <T> Collection<T> anyCollectionOf(Class<T> clazz);

Solution 3 - Java

if you use a own method, you can even use static import:

private Collection<Person> anyPersonCollection() {
    return any();
}

Then you can use

verify(someService).process(anyPersonCollection());

Solution 4 - Java

As an alternative to the accepted answer you can try:

verify(someService).process(Mockito.<SomeGenericClass<Person>>any());

Where I used org.mockito.Mockito instead of Matchers.

Solution 5 - Java

You can't express this because of type erasure. Even if you could express it in code, Mockito had no chance to check it at runtime. You could create an interface like

interface PersonCollection extends Collection<Person> { /* nothing */ }

instead and use this throughout your code.

Edit: I was wrong, Mockito has anyCollectionOf(..) which is what you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSvishView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavaseblmView Answer on Stackoverflow
Solution 3 - JavafxaView Answer on Stackoverflow
Solution 4 - JavaOleksandr TarasenkoView Answer on Stackoverflow
Solution 5 - JavaWaldheinzView Answer on Stackoverflow