本文介紹了mockito ArrayList<String>問題的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個方法,我正在嘗試進行單元測試.此方法將參數作為 ArrayList 并對其進行處理.我試圖定義的模擬是:
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);
這會給出 [unchecked] unchecked conversion"警告.
which gives a [unchecked] unchecked conversion" warning.
ArrayList<String> mocked = mock(ArrayList<String>.class);
給我一??個錯誤.
有人愿意告訴我我做錯了什么嗎?
Anyone care to enlighten me as to what I am doing wrong?
推薦答案
替代方案是使用@Mock注解,因為Mockito可以使用類型反射來找到泛型類型:
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);
}
}
這篇關于mockito ArrayList<String>問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!