Search code examples
springspring-transactionsspring-test

How to rollback back one method and commit second one in test


I have some code like follows

@Test
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void testCallDb() {
    rollbackThis();
    commitThis();
}

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
@Commmit
public void commitThis() {
    //do some work and commit
}

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
@Rollback
public void rollbackThis() {
    //do some work and rollback
}

When I run this, it always rolls back, both methods, i.e. it doesn't commit the commitThis() method data. If I put a @Commit on testCallDb() then both methods are committed, including the rollbackThis() method which I want to rollback.

Is there any solution to this either using Spring annotations (preferably) or using some other method?

Update: As a solution, I used @Huy's suggestion, i.e. removed annotations from commitThis() and rollbackThis() and changed body of testCallDb() to:

rollbackThis();
TestTransaction.flagForRollback();
TestTransaction.end();
TestTransaction.start();
TestTransaction.flagForCommit();
commitThis();

Solution

  • Since Spring Framework 4.1, you can interact with test-managed transactions programmatically by using the static methods in TestTransaction.

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/transaction/TestTransaction.html

    Hope it help in your case.