我有一个 Spring Boot 应用程序并使用 @SpringBootTest
进行测试。
我试图让我的数据库在每次测试时都处于相同的状态。
我的测试类用 @Transactional
和 @Rollback
注释。
我正在测试的服务也用@Transactional
进行注释。
据我了解,在激活 TransactionManager TRACE 日志时,Spring Boot 应用程序事务已提交,测试事务已按预期回滚。
问题源于这样一个事实:我的设置创建了 2 个不同的事务:一个用于测试,一个用于应用程序。
你知道我可以做什么来让测试中创建的交易在应用程序中相同吗?
示例代码:
https://github.com/sey/transactional
您将看到 GreetingsResourceTest 失败,因为我认为有 2 个不同的上下文不共享事务。
但是 GreetingsServiceTest 可以按预期工作,因为测试期间没有创建特定的应用程序上下文。
最佳答案
Spring 有一个传播级别 e,它表示与事务注释一起使用的事务传播行为。这是您可以覆盖 Spring 如何使用 @Transactional 创建事务的唯一方法:
MANDATORY
Support a current transaction, throw an exception if none exists.
NESTED
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
Support a current transaction, create a new one if none exists.
REQUIRES_NEW
Create a new transaction, and suspend the current transaction if one exists.
SUPPORTS
Support a current transaction, execute non-transactionally if none exists.
关于java - 使 @Transactional 和 @Rollback 与 Spring Boot Test 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52308023/