210

Mockito offers:

when(mock.process(Matchers.any(List.class)));

How to avoid warning if process takes a List<Bar> instead?

4 Answers 4

328

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)));
Sign up to request clarification or add additional context in comments.

4 Comments

Note: this is deprecated in Mockito 2.* and will be removed in Mockito 3. Deprecated because Java 8 compiler can infer the type now.
@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
Better to use anyListOf. Even though anyList works, it emits a warning.
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> and List<DTO> I've solved this problem using ArgumentMatchers with generic: when(adapter.adapt(ArgumentMatchers.<DTO>anyList())).thenCallRealMethod();
28

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.

3 Comments

Matchers.any() is very convenient!
Matchers 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/…
@oddmeter Changes made.
17

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());

Comments

3

I needed anyList() with a typed ArrayList, the following worked:

(ArrayList<Bar>) ArgumentMatchers.<Bar>anyList()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.