Mockito.any() pass Interface with Generics

2019-01-10 03:29发布

问题:

is it possible to pass the type of an interface with generics?

The interface:

public interface AsyncCallback<T>

In my test method:

Mockito.any(AsyncCallback.class)

Putting <ResponseX> behind or for .class didnt work.

回答1:

There is a type-safe way: use ArgumentMatchers.any() and qualify it with the type:

ArgumentMatchers.<AsyncCallback<ResponseX>>any()

as pierrefevrier mentioned in the comments, with the new versions of Mockito it's

Matchers.<AsyncCallback<ResponseX>>any()


回答2:

Using Java 8, you can simply use any() (assuming static import) without argument or type parameter because of enhanced type inference. The compiler now knows from the target type (the type of the method argument) that you actually mean Matchers.<AsyncCallback<ResponseX>>any(), which is the pre-Java 8 solution.



回答3:

I had to adopt the following mechamism to allow for generics:

import static org.mockito.Matchers.any;
List<String> list = any();
when(callMyMethod.getResult(list)).thenReturn(myResultString);

Hope this helps someone.



回答4:

Posting pierrefevrier comment as answer which might be useful if it present in a answer instead of comments.

With new versions of Mockito: (Matchers.<AsyncCallback<ResponseX>>any()



回答5:

Further to thSoft's answer putting the qualified call to any() in method meant I could remove the qualification since the return type allowed inference:

private HashMap<String, String> anyStringStringHashMap() {
    return Matchers.any();
}


回答6:

You can just cast it, adding suppress warnings if you like:

@SuppressWarnings("unchecked")    
AsyncCallback<ResponseX> callback = Mockito.any(AsyncCallback.class)

If Java allowed 'generic' generics they could have a method like this which is what you are looking for

private static <T, E> T<E> mock(Class<T<E>> clazz)