Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
jwepurchase Avatar asked Dec 21 '14 05:12

jwepurchase


Video Answer


1 Answers

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:

@Captor
ArgumentCaptor<LinkedList<String>> captor;

@Before
public void init() {
   // initialize fields annotated with Mockito annotations
   MockitoAnnotations.initMocks(this);  
}
like image 65
azurefrog Avatar answered Oct 21 '22 03:10

azurefrog