jwepurchase jwepurchase - 4 months ago 12
Java Question

Why does the java compiler give "rawtypes" warning for class literal?

I'm using mockito to write some tests, and I'm using the following bit of code:

ArgumentCaptor<LinkedList> captor = ArgumentCaptor.forClass(LinkedList.class);

This compiles and runs just fine, except for the warning that "captor" is raw type and I should replace it with something like:

ArgumentCaptor<LinkedList<String>> captor = ArgumentCaptor.forClass(LinkedList<String>.class);

The problem is that LinkedList<String>.class doesn't exist, so the right side of the assignment will never compile.

Assuming that suppressing the warning is inelegant, is there an elegant solution? If not, why does the compile warn me about something I can't really fix?


There is a @Captor annotation in Mockito which is designed to allow you to avoid warnings like this.

Using it, you don't need to manually new up your ArgumentCaptor. You can just declare it with the annotation and then call MockitoAnnotations.initMocks(this); to "automatically" create your captor.

instead of this:

ArgumentCaptor<LinkedList> captor = ArgumentCaptor.forClass(LinkedList.class); 

do this:

ArgumentCaptor<LinkedList<String>> captor;

public void init() {
   // initialize fields annotated with Mockito annotations