junit rollback after transaction commit

AbstractTransactionalDataSourceSpringContextTests (from springframework spring-mock.jar) is used to provide atomic junit-tests that won’t affect database state. This kind of isolation is achieved by running each test in a transaction that is rolled back after each test-run.

The problem might start when you are using AbstractTransactionalDataSourceSpringContextTests with multiple sessions committing transactions (and commit cannot be rolled back, as you know). For this I propose a solution where you could turn off all commits but keep rollback functionality (of course only in junit test-environment, NOT in production).

Be aware that this solution has at least one weak spot:multiple connections can’t read data if commits are not actually executed. But you should try to avoid multiple-connections in your junit-tests anyway.

Are there any other problems? Let me know :)

Following example is providing rollback-only transaction support for hibernate:

If using spring, put following into SessionFactory hibernateProperties:
hibernate.transaction.factory_class=com.ahtik.RollbackTransactionFactory

and then have following classes in your classpath:

  • What can be the solution if I want to achieve rollback with multiple datasource using AbstractTransactionalDataSourceSpringContextTests?

    What can be the solution if I want to achieve rollback with multiple datasource using AbstractTransactionalDataSourceSpringContextTests?

  • http://www.wpcStylePuzzles.com Justin

    What if I want the commit to happen always without any rollback?

    • http://ahtik.com/blog Ahti Kitsik

      Not sure I understand, by default it always commits without any rollback. So this tweak is needed only to ensure a clean rollback.