如何在服务层为@Transactional 时回滚单元测试

How to rollback unit test while service layer is @Transactional

我正在使用 Spring Boot 1.5.2.RELEASE 并且我的服务 classes 带有

注释
@Service
@Transactional(rollbackFor = Exception.class)

我的单元测试 class 注释为:

@RunWith(SpringRunner.class)
@SpringBootTest

我希望在测试完成后回滚通过单元测试方法在数据库中所做的更改。

建议的解决方案之一 是在测试 class 上添加 @Transactional 注释,我试过了但是这个解决方案产生了一些问题,是吗有时测试事务会在服务事务完成之前回滚(即使没有抛出任何异常!)。

回滚测试还有其他好的方案吗?

如果没有更改默认行为,所有更改都将回滚。而且你没有 类 / transaction propagation level = REQUIRES_NEW 的方法,因为它启动独立事务并且可以与外部事务独立提交或回滚

Transaction rollback and commit behavior

By default, test transactions will be automatically rolled back after completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the @Commit and @Rollback annotations.

@Rollback

@Rollback indicates whether the transaction for a transactional test method should be rolled back after the test method has completed. If true, the transaction is rolled back; otherwise, the transaction is committed (see also @Commit). Rollback semantics for integration tests in the Spring TestContext Framework default to true even if @Rollback is not explicitly declared.

When declared as a class-level annotation, @Rollback defines the default rollback semantics for all test methods within the test class hierarchy. When declared as a method-level annotation, @Rollback defines rollback semantics for the specific test method, potentially overriding class-level @Rollback or @Commit semantics.

在测试 class 上带有 @Transactional 的解决方案是执行此操作的标准方法。 Spring Tx 不可能突然回滚事务,所以我建议仔细研究您遇到的问题,而不是发明其他解决方案。

来自docs

By default, test transactions will be automatically rolled back after completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the @Commit and @Rollback annotations.

您的评论:

sometimes the test transaction is rolled back (even without no exceptions thrown !) before the service transaction is completed !

对我来说没有意义。回滚了怎么知道 txn 完成了没有?异常对于测试来说并不重要,正如我在上面引用的文档。