Mockito: List Matchers with generics
Solution 1
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
Solution 2
In addition to anyListOf
above, you can always specify generics explicitly using this syntax:
when(mock.process(Matchers.<List<Bar>>any(List.class)));
Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:
when(mock.process(Matchers.any()));
Remember that neither any()
nor anyList()
will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class)
was changed to mean "any instanceof
Foo", but any()
still means "any value including null
".
NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers
. Older versions of Mockito will need to keep using org.mockito.Matchers
as above.
Solution 3
Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:
import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;
verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());
Related videos on Youtube
Philippe Blayo
One of the best experience in my life has been to enjoy pair programming with developers that value clean code and simple design. It's called eXtreme Programming and I hope one day I'll have the opportunity to do it again.
Updated on February 15, 2022Comments
-
Philippe Blayo about 2 years
Mockito offers:
when(mock.process(Matchers.any(List.class)));
How to avoid warning if
process
takes aList<Bar>
instead? -
MBach almost 8 years
Matchers.any()
is very convenient! -
Kip over 7 yearsNote: this is deprecated in Mockito 2.* and will be removed in Mockito 3. Deprecated because Java 8 compiler can infer the type now.
-
oddmeter about 7 yearsMatchers is now deprecated, here's the info from mockito "Use ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest org.hamcrest.Matchers class. This class will likely be removed in version 3.0." static.javadoc.io/org.mockito/mockito-core/2.7.21/org/mockito/…
-
Jeff Bowman about 7 years@oddmeter Changes made.
-
Fernando Fradegrada almost 7 years@artbristol do you know if with anySet() should work as same as anyList()? I am in Java 8 and a warning is thrown in Eclipse IDE
-
balki over 6 yearsBetter to use
anyListOf
. Even thoughanyList
works, it emits a warning. -
edufinn almost 5 years
anyListOf
is deprecated, so it is better NOT to use it. Example for Java 8 doesn't work in case of method overload, for example if you have a method accepting 2 different lists:List<DBEntity>
andList<DTO>
I've solved this problem usingArgumentMatchers
with generic:when(adapter.adapt(ArgumentMatchers.<DTO>anyList())).thenCallRealMethod();
-
Sharm almost 3 yearsWorks perfectly, Thankyou