在单元测试期间模拟数据源
即使数据库已关闭,我也想对我的独立于数据库的 Web 层控制器进行单元测试。
但是 transactionManager
bean 实例化失败,因为使用给定的数据库凭据的 bean dataSource
无法实现连接。
另外,我还使用了 @Transactional
、@AfterTransaction
和 @BeforeTransaction
注释,但我不想删除它们。
有没有办法定义一个虚拟(或模拟)dataSource
,我不需要提供任何数据库凭据,但仍然可以实例化我的transactionManager
bean?
I would like to unit test my DB independent web layer controllers even if the database is down.
But the transactionManager
bean instantiation fails because the connection cannot be achieved by the bean dataSource
with the given DB credentials.
Also, I have used @Transactional
, @AfterTransaction
and @BeforeTransaction
annotations which I do not want to remove.
Is there a way to define a dummy (or mock) dataSource
where I need not provide any database credentials but still get my transactionManager
bean to be instantiated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所描述的更多的是集成测试而不是单元测试。对于单元测试,不要启动 Spring 或事务管理器。只需实例化您的控制器并对其进行单元测试即可。对于集成测试,请考虑仅使用 H2 内存数据库。 H2 速度极快(比 Derby 快得多),并且非常适合在需要数据库时进行测试。
What you're describing is more of an integration test than a unit test. For unit testing, don't start Spring or the transaction manager. Just instantiate your controller and unit test it. For integration tests, consider just using an H2 in-memory database. H2 is extremely fast (much faster than Derby) and excellent for testing when a database is needed.
Spring 教程中对此进行了介绍。您必须创建 DAO 的内存版本。
查看 6.2 修复失败的测试
This is covered in the Spring turtorials. You have to create an in InMemory version of your DAO's.
Look at 6.2 Fix the failing tests
使用依赖注入。您有两个标准且有据可查的选项来执行此操作。
Use dependency injection. You have two standard and well documented options to do this.