验证场景的事务性 Spring Junit4 测试用例

发布于 2024-12-21 02:26:50 字数 981 浏览 4 评论 0原文

我正在使用 Spring,JPA 使用 hibernate 进行服务 -> dao层。 事务由 spring 管理。 我有验证测试用例,其中我需要验证重复数据插入并引发异常。

在我的测试用例中,它扩展为 AbstractTransactionalJUnit4SpringContextTests

我已将 @TransactionConfiguration 配置为 defaultRollback 为 true 并为事务管理器配置了 bean 名称(在我的例子中,它是 JpaTransactionManager 的一个 bean)

我按以下步骤执行此测试用例

  1. 通过调用 dao.create(entity); 创建一条记录; (这将会成功)

  2. 创建一条相同的记录(所有属性与步骤1中设置的相同)并调用dao.create(entity)(这一定会失败,但不会失败)

  3. 在我的 create(entity) 方法中,我调用 validate() 方法,该方法触发标量对象查询(JPQL) 进行验证。

我预计验证会失败,但这毫无例外,并且重复的数据会插入到数据库中。

我尝试调试(启用休眠日志),我发现选择查询(标量查询)无法获取正确的数据(理想情况下它应该获取至少 1 条记录,因为我在上面列出的步骤 1 中为其插入了数据。)

我看到在选择查询进行验证之前,在日志中插入第 1 步的查询。

有没有其他方法可以为这种涉及 spring / jpa 和 hibernate 的场景编写测试用例?

请发表您的看法

提前致谢!

I am using Spring,JPA using hibernate for service -> dao layer.
Transactions are spring managed.
I have validation testcase wherein , I need to validate for duplicate data insertion and throw an exception.

In my testcase ,which is extension to AbstractTransactionalJUnit4SpringContextTests

I have configured @TransactionConfiguration with defaultRollback as true and bean name for transaction manager (in my case its a bean of JpaTransactionManager)

I execute this testcase as below steps

  1. Create a record with call to dao.create(entity); (this will succeed)

  2. Create a same record (with all the attributes same as set in step 1) and call dao.create(entity) (this must fail, but its not failing)

  3. In my create(entity) method I make call to validate() method, which fires scalar object query (JPQL) to validate.

I expect validation to be failed, but this works without exception and duplicate data gets inserted in DB.

I tried debugging (enabled hibernate logs),I found that the select query (scalar query) fails to get the proper data (ideally it should fetch at least 1 record, as I inserted data for it in step 1 listed above.)

I see Insert query for step1 in logs ,before select query for validation.

Is there any other way to write test case for such scenario which involves spring / jpa with hibernate?

Please post your views

Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

橘香 2024-12-28 02:26:50

您能否将您的测试粘贴到此处,我相信每个测试都在自己的事务中运行,并且您将 defaultRollback 设置为 true。这应该是问题所在。

Can you please paste your test here, I believe each test is running in its own transaction, and you have defaultRollback as true. That should be the issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文