简体   繁体   English

如何在 Spring 中为事务方法编写事务单元测试?

[英]How to write Transactional Unit Tests for Transactional Methods in Spring?

The Unit-Test Classes I have in my Project extend an AbstractUnitTest class which is @Transactional .我在项目中的单元测试类扩展了一个AbstractUnitTest类,它是@Transactional The tests in these classes are running on some methods which themselves are @Transactional .这些类中的测试正在一些方法上运行,这些方法本身就是@Transactional

Whenever these methods bring tested fail, instead of rolling back, the Transactions are partially persisted ( in the Testing Environment, ordinarily they behave atomically ).每当这些方法导致测试失败时,事务不会回滚,而是部分持久化(在测试环境中,通常它们以原子方式运行)。 This is preventing me from testing Transactional behavior of my Project Modules.这阻止我测试我的项目模块的事务行为。

More specifically , I have a Unit-Test for an addList() method.更具体地说,我有一个addList()方法的单元测试。 However, on encountering an Exception, during unit-testing, the input list is partially added and not rolled back since , the test is itself running in a Transaction(by virtue of AbstractUnitTest being Transactional)然而,在单元测试过程中遇到一个异常,输入列表被部分加入,而不是因为,试验本身是在事务运行(凭借回滚AbstractUnitTest是事务)

On removing the @Transactional from AbstractUnitTest , the tests work fine.AbstractUnitTest删除@Transactional后,测试工作正常。 What is the reason for this behavior and how can you perform unit-testing of Transactional methods if the Unit Test class itself is Transactional?这种行为的原因是什么,如果单元测试类本身是事务性的,你如何执行事务性方法的单元测试?

that depends on your configuration I think: if you want to start a transaction you need to configure a TransactionManager for your unit testing.我认为这取决于您的配置:如果您想启动一个事务,您需要为您的单元测试配置一个 TransactionManager。 As you use Spring make sure this is configured and the transaction boundaries (begin/commit or rollback) are defined to ensure the transactional behavior (rollback upon error).当您使用 Spring 时,请确保已配置并定义事务边界(开始/提交或回滚)以确保事务行为(错误时回滚)。

My advice is anyway to use TransactionalTestExecutionListener to always rollback after each test: in this way each test is independent as it always runs with the same data.我的建议是无论如何使用 TransactionalTestExecutionListener 在每次测试后总是回滚:这样每个测试都是独立的,因为它总是使用相同的数据运行。

Hope this helps.希望这可以帮助。

Beppe贝佩

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM