Ahti Kitsik
Building develper tools. Python, Java, JavaScript.

writings about @ahtik

junit rollback after transaction commit

By Ahti Kitsik, 18 May 2006

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:

@ahtik is on twitter!