EasyMock:如何在没有警告的情况下创建泛型类的模拟?
该代码
private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);
向我发出警告“类型安全:SomeClass 类型的表达式需要未经检查的转换才能符合 SomeClass
The code
private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);
gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
AFAIK,当涉及类名文字时,您无法避免未经检查的警告,并且
SuppressWarnings
注释是处理此问题的唯一方法。请注意,尽可能缩小
SuppressWarnings
注释的范围是一种很好的形式。 您可以将此注释应用于单个局部变量赋值:或使用辅助方法:
AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the
SuppressWarnings
annotation is the only way to handle this.Note that it is good form to narrow the scope of the
SuppressWarnings
annotation as much as possible. You can apply this annotation to a single local variable assignment:or use a helper method:
我通过引入一个子类来解决这个问题,例如
然后创建该抽象类的模拟:
I worked around this problem by introducing a subclass, e.g.
Then create a mock of that abstract class:
两个明显的途径是抑制警告或模拟子类。
(免责声明:我什至没有尝试编译此代码,也没有使用过 EasyMock。)
The two obvious routes are to suppress the warning or mock a subclass.
(Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)
您可以使用
@SuppressWarnings("unchecked")
注释测试方法。 我同意这是一种黑客行为,但在我看来,它在测试代码上是可以接受的。You can annotate the test method with
@SuppressWarnings("unchecked")
. I agree this is some what of a hack but in my opinion it's acceptable on test code.我知道这违背了问题,但为什么不创建一个列表而不是模拟列表呢?
它的代码更少,更容易使用,例如,如果您想将项目添加到列表中。
代替
I know this goes against the question, but why not create a List rather than a Mock List?
It's less code and easier to work with, for instance if you want to add items to the list.
Instead of