Database Unit Testing - CRUD Testing

Jakob Jenkov
Last update: 2014-05-24

If you need to test a DAO or DAO like component, you will need to test that all of inserts, reads, updates and deletes work as expected. These operations are often abbreviated CRUD (Create Read Update Delete).

Rather than writing a separate unit test method for each operation (insert, read, update, delete), it can be easier to test all 4 operations inside the same test method. That way, you don't have to insert records into the database inside the update and delete test methods. You just reuse the data inserted earlier in the single CRUD test method.

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", "one");
    myDao.insertABC("2", "two");

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


    myDao.update("1", "oneOne");
    myDao.update("2", "twoTwo");

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

    
    myDao.delete("1");
    myDao.delete("2");

    assertNull(myDao.readABC("1"));
    assertNull(myDao.readABC("2"));

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

The test method first tests the inserts, then uses the read methods to test if both the insert and read method works.

Second, the test method updates the records in the database, and again uses the read methods to help verify that the update methods works.

Third, the test deletes the records in the database again, and again uses the read methods to help verify that the delete methods works. The test thus also verifies, that the read method returns null if no data is found in the database, rather than throwing an exception.

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