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:

3 Comments

  1. 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?
    Posted October 27, 2006 at 2:54 pm | Permalink
  2. What if I want the commit to happen always without any rollback?

    Posted July 13, 2010 at 9:22 am | Permalink
    • Not sure I understand, by default it always commits without any rollback. So this tweak is needed only to ensure a clean rollback.

      Posted July 27, 2010 at 8:35 pm | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Protection by WP-SpamFree