弹簧& Mockito - 忽略传递依赖
我有一个如下所示的分层应用程序:
@PreAuthorize('isAuthenticated()')
@Controller
public class MyController {
@Autowired
MyService service;
}
@Service
public class MyService {
@Autowired
MyDao dao;
}
public interface MyDao {
}
@Repository
public class MyDaoImpl implements MyDao {
}
我想测试依赖于 AOP 的 @PreAuthorize
注释,因此我使用 SpringJUnit4ClassRunner
创建一个测试 AuthenticationManager< /code> 和
MyController
。
如果 @ContextConfiguration
不包含任何与 MyService
匹配的 bean,则测试初始化将失败,因为它无法解析该 bean。
如果我不需要 AOP,我会使用 Mockito 测试运行器并注入 Mockito.mock(MyService.class)
。但是,如果我尝试使用 spring runner 执行此操作,我的测试将再次失败,因为它无法解析服务的 MyDao
(即使该服务是模拟服务)。
我绝对不想模拟整个对象图。我宁愿它停止在嘲笑的服务上。我该怎么做呢?
I have a layered application that looks like this:
@PreAuthorize('isAuthenticated()')
@Controller
public class MyController {
@Autowired
MyService service;
}
@Service
public class MyService {
@Autowired
MyDao dao;
}
public interface MyDao {
}
@Repository
public class MyDaoImpl implements MyDao {
}
I want to test the AOP-dependent @PreAuthorize
annotation, so I use the SpringJUnit4ClassRunner
which creates a test AuthenticationManager
and MyController
.
If the @ContextConfiguration
does not include any bean matching MyService
, test initialization fails because it can't resolve the bean.
If I didn't need AOP, I would use Mockito test runner and inject Mockito.mock(MyService.class)
. But if I try and do it with spring runner, again my test fails because it can't resolve MyDao
for the service (even though the service a mock).
I definitely don't want to mock the whole object graph. I'd rather it stopped on the mocked service. How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 MyService 应该实现一个接口,并且您应该模拟该接口而不是类。那么您将不需要 DAO 实现。您可能还会遇到我在尝试在 Jersey 中测试 JAX-RS 资源类时遇到的类似问题。问题是如何将单个 bean 部署到 Spring 容器中,但模拟其依赖项。我写了一篇博客文章,可能会如果这是您面临的问题,可以帮助您解决。特别是,最终解决方案可能有帮助。
Your MyService should implement an interface, and you should mock the interface instead of the class. Then you won't need a DAO implementation. You might also, perhaps, be running into a similar issue that I faced while trying to test a JAX-RS resource class in Jersey. The problem is how to deploy a single bean into a Spring container but mock its dependencies. I wrote a blog post on it that might help you out if this is the problem you're facing. In particular, the final solution may be of help.