mockito ArrayList;问题
我有一个正在尝试进行单元测试的方法。此方法采用 ArrayList 形式的参数并使用它执行操作。我试图定义的模拟是:
ArrayList<String> mocked = mock(ArrayList.class);
它给出了[未经检查的]未经检查的转换”警告。
ArrayList<String> mocked = mock(ArrayList<String>.class);
给了我一个错误。
有人愿意启发我,让我知道我做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种方法是使用 @Mock 注释,因为这样 Mockito 就可以使用类型反射来查找泛型类型:
The alternative is to use the @Mock annotation since then Mockito can use type reflection to find the generic type:
ArrayList.class
是 Java 编译器不支持的构造。对于第一次尝试,您应该这样做:
发生这种情况是因为
mock
方法只能返回原始类型。一般来说,使用原始类型不好,因为这可能会导致运行时错误。在你的情况下,它完全没问题,因为你知道mocked
无论如何都不是一个真正的ArrayList
。只是关于 @SuppressWarnings( "unchecked" ) 注释的一般建议。尽量使其尽可能接近问题的根源。例如,您可以仅将其放置在变量声明中,也可以将其隐藏在整个方法中。一般来说,对变量抑制它,因为否则广泛的方法注释可以抑制函数中的其他问题。
ArrayList<String>.class
is a construct not supported by Java compiler.For you first try, you should do this:
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 thatmocked
is not a REALArrayList<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.