Java mockito ArrayList<String> 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2922320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mockito ArrayList<String> problem
提问by Sardathrion - against SE abuse
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 并使用它进行处理。我试图定义的模拟是:
ArrayList<String> mocked = mock(ArrayList.class);
which gives a [unchecked] unchecked conversion" warning.
这给出了 [unchecked] 未经检查的转换”警告。
ArrayList<String> mocked = mock(ArrayList<String>.class);
gives me an error.
给我一个错误。
Anyone care to enlighten me as to what I am doing wrong?
任何人都愿意启发我了解我做错了什么?
采纳答案by Steve N
The alternative is to use the @Mock annotation since then Mockito can use type reflection to find the generic type:
另一种方法是使用 @Mock 注释,因为那时 Mockito 可以使用类型反射来查找泛型类型:
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);
}
}
回答by Alexander Pogrebnyak
ArrayList<String>.classis a construct not supported by Java compiler.
ArrayList<String>.class是 Java 编译器不支持的构造。
For you first try, you should do this:
对于你第一次尝试,你应该这样做:
@SuppressWarnings( "unchecked" )
ArrayList<String> mocked = mock(ArrayList.class);
This happens because mockmethod 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 mockedis not a REAL ArrayList<String>anyway.
发生这种情况是因为mock方法只能返回原始类型。一般来说,使用原始类型并不好,因为这可能会导致运行时错误。在您的情况下,这完全没问题,因为您知道这无论如何mocked都不是真实ArrayList<String>的。
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.
只是关于@SuppressWarnings( "unchecked" )注释的一般建议。尽量让它靠近问题的根源。例如,您可以将它仅用于变量声明,或者您可以在整个方法中取消它。通常,为变量抑制它,否则广泛的方法注释会抑制函数中的其他问题。

