Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito ArrayList<String> problem

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?

like image 340
Sardathrion - against SE abuse Avatar asked May 27 '10 15:05

Sardathrion - against SE abuse


2 Answers

The alternative is to use the @Mock annotation since then Mockito can use type reflection to find the generic type:

public class MyTest {

  @Mock
  private ArrayList<String> mockArrayList;

  ...

  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  public void testMyTest() {
    when(mockArrayList.get(0)).thenReturn("Hello world");

    String result = mockArrayList.get(0);

    assertEquals("Should have the correct string", "Hello world", result);

    verify(mockArrayList).get(0);
  }
}
like image 89
Steve N Avatar answered Sep 26 '22 10:09

Steve N


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.

like image 26
Alexander Pogrebnyak Avatar answered Sep 26 '22 10:09

Alexander Pogrebnyak