开发者

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" warnin开发者_开发技巧g.

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

gives me an error.

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


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);
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜