How do you use Mockito matchers like `anyList()` with generics to avoid warnings?

In Mockito, using a matcher such as when(mock.process(Matchers.any(List.class))) works for methods expecting a List, but it triggers unchecked warnings when the method signature expects a generic type like List<Bar>.

What’s the correct way to use anyList() or similar matchers in Mockito to handle generic lists safely without compiler warnings?

This is a common problem when using generics with Mockito.

The key is to use the generic version of the matcher instead of any(Class) to avoid unchecked warnings.

For example, if your method expects List:

when(mock.process(Mockito.<Bar>anyList())).thenReturn(someResult);

The tells the compiler what type the matcher should expect, so it suppresses the unchecked warning.

Yep, exactly, I do the same thing in my projects.

Another trick: if you have multiple generic parameters, you can annotate the method with @SuppressWarnings(“unchecked”) locally, but using Mockito.anyList() is cleaner and safer because it keeps type checking intact.

Remember that anyList() works for any List type, but the compiler only knows the raw type unless you explicitly provide the generic like anyList().

If you’re mocking a method with Map<String, Bar> or other parameterized types, you can use the same pattern:

when(mock.process(Mockito.<String, Bar>anyMap())).thenReturn(someResult);

This approach avoids warnings and keeps your tests type-safe.