Search code examples
unit-testingtransactionsopenejb

EJB repository testing with OpenEJB - how to rollback changes


I try to test my EJB-based repositories using OpenEJB. Every time new unit test is runned I'd like to have my DB in an "initial" state. After the test, all changes should be rolled back (no matter if test succeeded or not). How to accomplish it in a simple way? I tried using UserTransaction - beginning it when test is starting and rolling back changes when finishing (as you can see below). I don't know why, but with this code all changes in DB (which were done during unit test) are left after line rolling changes back has been executed. As I wrote, I'd like to accomplish it in the simplest way, without any external DB schema and so on.

Thanks in advance for any hints!

Piotr

 public class MyRepositoryTest {

    private Context initialContext;

    private UserTransaction tx;

    private MyRepository repository; //class under the test

    @Before
    public void setUp() throws Exception {
        this.initialContext = OpenEjbContextFactory.getInitialContext();
        this.repository = (MyRepository) initialContext.lookup(
                "MyRepositoryLocal");
        TransactionManager tm = (TransactionManager) initialContext.lookup(
                "java:comp/TransactionManager");
        tx = new CoreUserTransaction(tm);
        tx.begin();
    }

    @After
    public void tearDown() throws Exception {
        tx.rollback();
        this.initialContext = null;
    }

    @Test
    public void test() throws Exception {            
        // do some test stuff
    }
}

Solution

  • There's an example called 'transaction-rollback' in the examples zip for 3.1.4.

    Check that out as it has several ways to rollback in a unit test. One of the techniques includes a trick to get a new in memory database for each test.