java - 使 @Transactional 和 @Rollback 与 Spring Boot Test 一起使用

标签 java spring spring-boot

我有一个 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/

相关文章:

spring - 使用 Liferay 进行 REST 服务中的身份验证和授权

java - Getters 和 Setters - 正确的约定

c# - 如何将附加数据传递到 Web 服务

java - Vaadin+Spring(不带 SpringBoot)与 JavaConfig

java - 如何正确设计Spring组件?

amazon-web-services - AWS Spring 启动应用程序上的 502 错误请求

asynchronous - 如何使用 Spring Boot 向 Controller 实现异步 REST 请求?

java - Spring Boot Multi-Tenancy 架构中的表同步

java - 将值传递给 JLabel

java - 使用 SSLSockets 的正确方法是什么?为什么会收到这些错误?