How to force transaction commit in Spring Boot test?
Use the helper class org.springframework.test.context.transaction.TestTransaction
(since Spring 4.1).
Tests are rolled back per default. To really commit one needs to do
// do something before the commit
TestTransaction.flagForCommit(); // need this, otherwise the next line does a rollback
TestTransaction.end();
TestTransaction.start();
// do something in new transaction
An approach would be to inject the TransactionTemplate
in the test class, remove the @Transactional
and @Commit
and modify the test method to something like:
...
public class CommitTest {
@Autowired
TestRepo repo;
@Autowired
TransactionTemplate txTemplate;
@Test
public void testCommit() {
txTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
repo.createPerson();
// ...
}
});
// ...
System.out.println("Something after the commit...");
}
Or
new TransactionCallback<Person>() {
@Override
public Person doInTransaction(TransactionStatus status) {
// ...
return person
}
// ...
});
instead of the TransactionCallbackWithoutResult
callback impl if you plan to add assertions to the person object that was just persisted.