Mockito: Verifying with generic parameters
39,715
Solution 1
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
Try :
verify(someService).process(anyCollectionOf(Person.class));
Since version 1.8 Mockito introduces
public static <T> Collection<T> anyCollectionOf(Class<T> clazz);
Solution 3
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());
Author by
Lemon
Software Developer, Geek, HSP, SDA, ..., open, honest, careful, perfectionist, ... Currently into indoor rowing and rock climbing, just to mention something non-computer-related... Not the best at bragging about myself... so... not sure what more to write... 🤔
Updated on July 05, 2022Comments
-
Lemon almost 2 years
With Mockito I can do the following:
verify(someService).process(any(Person.class));
But how do I write this if
process
takes aCollection<Person>
instead? Can't figure out how to write it correctly. Just getting syntax errors... -
Rogério almost 13 yearsActually, it could be expressed with a "type literal" object if the API accepted it:
any(new TypeLiteral<Collection<Person>>() {})
. Not pretty, of course, but it does work since all the type information is available at runtime (through Reflection or a bytecode library). -
Waldheinz almost 13 years@Rogerio: you are right, and it seems Mockito indeed supports this now. Haven't used it in a while...
-
Cristiano Fontes over 11 yearsThanks it works... but God it looks horrible, there have to be a nicer way to right that...
-
Adam Parkin over 10 yearsThumbs up on the only solution that answers the question as stated as opposed to targeting the special case of matching containers.
-
scubbo over 8 yearsThis answer is now incorrect. The answer below gives a better solution.
-
Elijah Lofgren over 7 yearsFor others who come to this and need it, there's also an anyListOf() in addition to anyCollectionOf(), see: stackoverflow.com/a/10512526/908677
-
Gabriel Falcone about 7 yearsI may be mistaken but I do not think this is the correct answer. Although it removes the warning, the verification switches from "any(Collection.class)" to any(), which does not verify anything. At least before there was a class check. Isn't it?
-
Rana Ghosh about 7 yearsHow did you get intellij to automatically suggest that to you?
-
Naxos84 over 6 yearsanyCollectionOf(Class<T> clazz) will be removed in Mockito 3.0 and java8. There will be a new method: anyOptional(Class<T> class) see: github.com/mockito/mockito/issues/308
-
Ray almost 5 years
Matchers
is deprecated, should now useArgumentMatchers
.