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 {

    userTransaction.begin();

    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());

        movies.callSetRollbackOnly();
    } finally {
        try {
            userTransaction.commit();
            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());

}