Wednesday March 10, 2010

Example: Testing Transaction Rollback

We've coded up a nice little example project that shows various ways to rollback transactions in unit tests.

The example also serves to show the various options in EJB that pertain to how to rollback transactions via either a UserTransaction, SessionContext.setRollbackOnly(), or throwing a RuntimeException. The example also shows how to mark a RuntimeException with @ApplicationException to bypass the rollback behavior.

Here's a snippet from the test case to show how simple it is to test:

 * Transaction is marked for rollback inside the bean via
 * calling the javax.ejb.SessionContext.setRollbackOnly() method
 * This is the cleanest way to make a transaction rollback.
public void testMarkedRollback() throws Exception {


    try {
        entityManager.persist(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
        entityManager.persist(new Movie("Joel Coen", "Fargo", 1996));
        entityManager.persist(new Movie("Joel Coen", "The Big Lebowski", 1998));

        List list = movies.getMovies();
        assertEquals("List.size()", 3, list.size());

    } finally {
        try {
            fail("A RollbackException should have been thrown");
        } catch (RollbackException e) {
            // Pass

    // Transaction was rolled back
    List list = movies.getMovies();
    assertEquals("List.size()", 0, list.size());



Thanks for showing various ways to roll back transactions in unit tests

Posted by jetbox on November 19, 2018 at 05:51 AM EST #

It is really interesting, Im very pleasantly impressed!

Posted by Amoxil on July 19, 2019 at 12:05 PM EDT #

I essentially needed to record a snappy word to express profound gratitude to you for those great tips and indications you are appearing on this site.

Posted by short motivational captions on October 14, 2019 at 07:11 AM EDT #

There are some alternate and most suitable ways to rollback transactions in unit tests which are extremely easy. Visit to get educational help. You guys should also try them because they are reliable and truly authentic.

Posted by Carl Niese on October 21, 2019 at 09:44 AM EDT #

Post a Comment:
Comments are closed for this entry.



Hot Blogs (today's hits)

Tag Cloud