问题描述
我有一个带有Spring Data Rest的Spring Boot应用程序,并且在集成测试中将@WebIntegrationTest
和TestRestTemplate
一起使用.测试的基类如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = "test")
@SpringApplicationConfiguration(classes = Application.class)
@Transactional
@TransactionConfiguration
@WebIntegrationTest("server.port: 0")
public abstract class IntegrationTest {
...
}
我正在通过使用TestRestTemplate
对资源执行POST
请求来测试实体的创建.问题在于,即使我的测试配置为事务性的,持久保存数据库中实体的事务也不会回滚,因此该实体在测试后仍保留在数据库中.我有点理解,因为在测试中回滚的事务与持久化实体的事务不同.
现在我的问题是,有没有办法回滚通过测试方法通过RestTemplate
发出的请求触发的交易?
不.无法回滚已部署的应用程序管理的事务.
当您用@WebIntegrationTest
和@SpringApplicationConfiguration
注释测试类时,Spring Boot将启动嵌入式Servlet容器并在其中部署应用程序.因此,从这个意义上讲,您的测试和应用程序在两个不同的进程中运行.
Spring TestContext Framework 仅管理测试管理的交易.因此,测试类中@Transactional
的存在只会影响本地测试管理的事务,而不会影响处于不同过程的事务.
正如其他人已经提到的那样,一种解决方法是在测试完成后重置数据库的状态.为此,您有几种选择.查阅执行SQL脚本此致
Sam(Spring TestContext Framework的作者)
I have a Spring Boot application with Spring Data Rest and I use @WebIntegrationTest
along with the TestRestTemplate
in my integration tests. The base class for the tests looks something like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = "test")
@SpringApplicationConfiguration(classes = Application.class)
@Transactional
@TransactionConfiguration
@WebIntegrationTest("server.port: 0")
public abstract class IntegrationTest {
...
}
I was testing the creation of an entity by using the TestRestTemplate
to perform a POST
request to a resource. The problem is that the transaction that persists the entity on the database is not rolled back even thought my tests are configured to be transactional, so the entity remains on the database after the test. I kind of understand that because the transaction being rolled back in the test is not the same one persisting the entity.
Now my question is, is there any way of rolling back the transactions triggered by the requests made through the RestTemplate
in a test method?
No. It is not possible to roll back the transactions managed by your deployed application.
When you annotate your test class with @WebIntegrationTest
and @SpringApplicationConfiguration
, Spring Boot will launch an embedded Servlet container and deploy your application in it. So in that sense, your test and application are running in two different processes.
The Spring TestContext Framework only manages Test-managed transactions. Thus, the presence of @Transactional
on your test class only influences local test-managed transactions, not those in a different process.
As someone else already mentioned, a work-around would be to reset the state of the database once your test has completed. For this you have several options. Consult the Executing SQL scripts section of the reference manual for details.
Regards,
Sam (author of the Spring TestContext Framework)
这篇关于Spring Boot @WebIntegrationTest和TestRestTemplate-是否可以回滚测试事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!