在单元测试期间模拟数据源

发布于 2024-11-28 06:41:22 字数 383 浏览 4 评论 0原文

即使数据库已关闭,我也想对我的独立于数据库的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枕花眠 2024-12-05 06:41:22

您所描述的更多的是集成测试而不是单元测试。对于单元测试,不要启动 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.

落花随流水 2024-12-05 06:41:22

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

徒留西风 2024-12-05 06:41:22

使用依赖注入。您有两个标准且有据可查的选项来执行此操作。

  1. 使用 Google Guice 等框架。这样做会产生一些开销,但它将帮助您编写更好、更可测试的代码,并且具有一些很酷的功能,例如对 Web 层特别有用的范围界定。
  2. 通过添加采用数据源参数或数据源 setter 方法的构造函数,在您自己的代码中实现 DI。在生产中,您将传入/设置生产数据库,但在单元测试中,您可以使用模拟数据源,它只记录您的操作/事务。

Use dependency injection. You have two standard and well documented options to do this.

  1. Use a framework such as Google Guice. There will be some overhead for doing this, but it will help you write better, more testable code and has some cool features like scoping which is particularly helpful for web layers.
  2. Implement DI in your own code by adding a constructor which takes a datasource paramater or a datasource setter method. In production you will pass-in/set your production database but in unit testing you can use a mock datasource which simply logs your operations/transactions.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文