如何 EasyMock 调用返回通配符泛型的方法?
我们正在考虑切换到 Spring 3.0,并遇到 Spring 3.0、EasyMock 和 Java Generics 交叉的问题。
在一个地方,我们正在模拟 Spring 3.0 AbstractBeanFactory,特别是这个方法:
public Class<?> getType(String name) throws NoSuchBeanDefinitionException { ... }
在 Spring 的早期版本中,这会返回一个非泛型,一切都很好。然而,对于泛型,我们遇到了麻烦:
expect(mockBeanFactory.getType(CLASS_NAME)).andReturn(SOME_CLASS);
因为 getType
返回 Class
,andReturn
需要 Class<; ?>
作为参数,它根本无法正常工作。
有已知的解决方法吗?
We're looking at switching to Spring 3.0 and running into problems with the intersection of Spring 3.0, EasyMock, and Java Generics.
In one place, we're mocking a Spring 3.0 AbstractBeanFactory, specifically this method:
public Class<?> getType(String name) throws NoSuchBeanDefinitionException { ... }
Under earlier versions of Spring, this returns a non-generic and all was well. With the generic, however, we run into trouble with this:
expect(mockBeanFactory.getType(CLASS_NAME)).andReturn(SOME_CLASS);
Because getType
returns Class<?>
, andReturn
requires Class<?>
as a parameter, which simply doesn't work properly.
Is there a known workaround to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我以前用 Mockito 时也遇到过这样的问题。我还不确定为什么会发生这种情况。您可以将 Expect(..) 参数强制转换为非泛型 Class 类型,然后
您将收到一个警告,如果您愿意,可以将其抑制。这不是一个非常优雅的解决方案;我将再花几分钟查看它。
I've run into a problem like this before, with Mockito. I'm not sure why it happens yet. You can cast the expect(..) argument to the non-generic Class type, ala
Then you'll just have a warning, which you can suppress if you want. Not a very elegant solution; I'm going to spend a few more minutes looking at it.
避免任何转换和警告的最简单方法是使用
expectLastCall()
而不是expect(..)
(请参阅 我对类似问题的回答了解详情)。所以在这种情况下:
The easiest thing to avoid any casting and warnings is to use
expectLastCall()
instead ofexpect(..)
(see my answer to a similar question for details).So in this case: