Mockito: validation using general parameters

With Mockito, I can do the following:

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

But how to write it if process accepts Collection<Person> instead? I can’t understand how to write correctly. Just get syntax errors ...

+58
java generics parameters mockito verification
May 30 '11 at 11:34
source share
4 answers

Try:

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

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

+98
May 30 '11 at 11:44
source share

Try:

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

Since version 1.8 Mockito introduces

 public static <T> Collection<T> anyCollectionOf(Class<T> clazz); 
+19
Sep 18 '13 at 11:56 on
source share

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

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

Then you can use

 verify(someService).process(anyPersonCollection()); 
+1
Apr 6 '16 at 17:44
source share

You cannot express this due to type erasure. Even if you could express it in code, Mockito did not have the ability to test it at run time. You can create an interface, for example

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

and use it in all your code.

Edit: I was wrong, Mockito has anyCollectionOf (..) that you need.

-one
May 30 '11 at 11:42
source share



All Articles