Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot @WebIntegrationTest and TestRestTemplate - Is it possible to rollback test transactions?

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?

like image 443
Daniel Francisco Sabugal Avatar asked Apr 17 '15 11:04

Daniel Francisco Sabugal


1 Answers

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)

like image 142
Sam Brannen Avatar answered Oct 20 '22 23:10

Sam Brannen