Mockito: List Matchers with generics
Mockito offers:
when(mock.process(Matchers.any(List.class)));
How to avoid warning if process
takes a List<Bar>
instead?
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)));
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.
上一篇: Matcher在访问组之后抛出IllegalStateException
下一篇: Mockito:列出泛型的匹配器