如何在基于代理的Spring bean中设置模拟对象?
我在尝试在测试用例的有线 bean 中设置模拟对象时遇到问题。
这是我的简化问题:-
class SomeClassTest {
@Autowired
private SomeClass someClass;
@Test
public void testRun() {
Service service = mock(ServiceImpl.class);
when(service.doIt()).thenReturn("");
// this line fails with ClassCastException
((SomeClassImpl) someClass).setService(service);
assertEquals("bad", someClass.run());
}
}
interface SomeClass {
String run();
}
class SomeClassImpl implements SomeClass {
private Service service;
public void setService(Service service) {
this.service = service;
}
public String run() {
String value = service.doIt();
return StringUtils.isBlank(value) ? "bad" : "good";
}
}
interface Service {
String doIt();
}
class ServiceImpl implements Service {
public String doIt() {
return "bla";
}
}
在这个示例中,我尝试通过模拟 Service.doIt()
来测试 SomeClass
,以便我可以测试不同的条件。我面临的问题是我不确定应该如何在 SomeClass
中设置模拟服务对象。我能想到的唯一方法是将 SomeClass
向下转换为具体类来调用 setService(...)
,但是,我收到一个 ClassCastException 说 $Proxy 与 SomeClassImpl 不兼容。我相信我所有的 bean 连接都是基于代理的,因为我使用 AOP 来配置事务。我真的不想在 SomeClass
接口中公开 setService(...)
,因为在我的生产代码中这样做是没有意义的。
我有办法实现这个目标吗?
谢谢。
I'm having problems trying to set the mock object in my wired bean in my testcase.
Here's my simplified problem:-
class SomeClassTest {
@Autowired
private SomeClass someClass;
@Test
public void testRun() {
Service service = mock(ServiceImpl.class);
when(service.doIt()).thenReturn("");
// this line fails with ClassCastException
((SomeClassImpl) someClass).setService(service);
assertEquals("bad", someClass.run());
}
}
interface SomeClass {
String run();
}
class SomeClassImpl implements SomeClass {
private Service service;
public void setService(Service service) {
this.service = service;
}
public String run() {
String value = service.doIt();
return StringUtils.isBlank(value) ? "bad" : "good";
}
}
interface Service {
String doIt();
}
class ServiceImpl implements Service {
public String doIt() {
return "bla";
}
}
In this example, I'm trying to test SomeClass
by mocking out Service.doIt()
so that I can test different conditions. The problem I'm facing is I'm not sure how exactly I should set the mock Service object in SomeClass
. The only way I can think of is to downcast SomeClass
into the concrete class to call setService(...)
, however, I'm getting a ClassCastException saying $Proxy incompatible with SomeClassImpl. I believe all my bean wirings are proxy-based because I'm using AOP to configure the transaction. I really do not want to expose setService(...)
in SomeClass
interface because it makes no sense to do so in my production code.
Is there a way for me to accomplish this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 @Resource 注释来 获取实现:
You can use the @Resource annotation to get the implementation:
或
or