views:

137

answers:

1

I have a method that I am trying to unit test. This method takes a parameter as an ArrayList and does things with it. The mock I am trying to define is:

ArrayList<String> mocked = mock(ArrayList.class);

which gives a [unchecked] unchecked conversion" warning.

ArrayList<String> mocked = mock(ArrayList<String>.class);

gives me an error.

Anyone care to enlighten me as to what I am doing wrong?

+2  A: 

ArrayList<String>.class is a construct not supported by Java compiler.

For you first try, you should do this:

@SuppressWarnings( "unchecked" )
ArrayList<String> mocked = mock(ArrayList.class);

This happens because mock method can only return a raw type. In general it is not good to use the raw types because this may lead to runtime errors. In your case it's perfectly fine, because you know that mocked is not a REAL ArrayList<String> anyway.

Just a general advise about @SuppressWarnings( "unchecked" ) annotation. Try to keep it as close to the source of the problem as possible. For example you may put it just for the variable declaration, or you can suppress it for the whole method. In general suppress it for a variable, because otherwise the broad method annotation can suppress other problems in your function.

Alexander Pogrebnyak
As a side note, this particular problem is discussed as Item 24 (on pages 116-118) of Effective Java, Second Edition. The entire Generics chapter is available as a PDF on Sun's site: http://java.sun.com/docs/books/effective/generics.pdf
R. Bemrose
That makes sense. In general I dislike ignoring warnings but I was not aware you could ignore just one line. Thanks.
Sardathrion