Search code examples
javaspringspring-boottransactionsspring-transactions

Spring: Rollback transactin in Unittest


I have a complex service method, that loads a lot of data from the db. Since it only reads and validates data I want to make sure

  1. JPA (Hibernate) does not waste time for checking the big persistence context for changes.
  2. No accidental changes to the data are written to the db.

Therefore towards the end of my service I have this code

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()

My unit tests have mocks for all db access, so transactioning is not an issue. (I have integration test with @SpringBootTest and full trx support as well.) Unfortunately the rollback statement fails in pure unit tests.

Is there an easy way to get the rollback statement just do nothing in case of a unit test?


Solution

  • For now I just wrote a small component which is easy to mock:

    @Component
    public class RollBacker {
    
        public void setRollBackOnly() {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    
    }
    

    After all it's the singleton approach of TransactionAspectSupport which makes unit testing difficult here. IMHO TransactionAspectSupport should be a spring bean.