Java 使用Spring引导测试使@Transactional和@Rollback工作

Java 使用Spring引导测试使@Transactional和@Rollback工作,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个Spring Boot应用程序,并使用@SpringBootTest 我正在尝试使我的数据库在每次测试中处于相同的状态。 我的测试类用@Transactional和@Rollback注释 我正在测试的服务也用@Transactional 据我在激活TransactionManager跟踪日志时所了解,Spring Boot应用程序事务已提交,测试事务按预期回滚。 这个问题源于我的设置创建了两个不同的事务:一个用于测试,一个用于应用 你知道我该怎么做才能让在测试中创建的事务与在应用程序中创

我有一个Spring Boot应用程序,并使用
@SpringBootTest

我正在尝试使我的数据库在每次测试中处于相同的状态。
我的测试类用
@Transactional
@Rollback
注释
我正在测试的服务也用
@Transactional

据我在激活TransactionManager跟踪日志时所了解,Spring Boot应用程序事务已提交,测试事务按预期回滚。
这个问题源于我的设置创建了两个不同的事务:一个用于测试,一个用于应用

你知道我该怎么做才能让在测试中创建的事务与在应用程序中创建的事务相同吗

示例代码:

您将看到GreetingsResourceTest失败,因为我认为有两种不同的上下文不共享事务。

但是,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.

1) 您不需要回滚,因为如果存在事务,Spring引导测试总是回滚事务。2) 为什么你认为有两个交易?Spring启动测试将同一事务传播到您的服务。显示您的测试。我添加了一个示例项目来演示我的问题。如果你能看一看,告诉我什么是错误的配置。正如@SimonMartinelli所说,我没有将
@Rollback
放在测试中,因为默认行为是回滚事务。