Database Unit Testing - Rollback Transactions

Jakob Jenkov
Last update: 2014-05-24

If you are testing a component that uses a database, e.g. a DAO class, you may want to test that the component really inserts data into the database, updates it etc.

When testing if database components work correctly, you often have to insert a lot of data into the database, so the components have some data to work on. Unfortunately, this also means that you have to clean up all that data, when the unit test finishes, in order not to disturb other unit tests that setup data too.

A smart way to achieve this is by running the unit test inside a transaction. All data is inserted, read etc. inside the same transaction. When the unit test finishes, you can just rollback the transaction, and all the inserted data will be gone.

Here is a simple template showing you how to do this:


@Test
public void testIt() throws Exception {

  Connection connection = getConnection();
  connection.setAutoCommit(false);    //begin transaction

  MyDao      myDao      = new MyDaoImpl(connection);

  try{
    
    myDao.insertABC("1");
    myDao.insertABC("2");

    assertEquals("1", myDao.readABC("1"));
    assertEquals("2", myDao.readABC("2"));

  } finally {
    connection.rollback();
    connection.close();
  }  
}

It is possible that your persistence technology does not allow you to access the database connection directly. But, usually you can still control the underlying transaction, and thus start and rollback a transaction.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next