Database Unit Testing - Test Data Creation

Jakob Jenkov
Last update: 2014-05-24

Some applications need extensive test data inserted into the database in order to properly test the applications domain logic. Setting up all this data in each and every unit test can be quite cumbersome.

Instead you could create a "test case" object, which is capable of setting up data for simple test cases. For instance, inserting a customer in the database, with N products selected etc.

Here is a simple example of such a TestData class. It is just a standard Java class - nothing secret about it.

public class TestData {

    public void insertCustomer() {
      // insert customer logic.
    }

    public void insertProducts() {
      // insert products for customer
    }

    pubic void setupCustomerSituation() {
      // insert customer with several products, in
      // various configurations.

    }

    //etc.

}

Exactly what methods you will put in your own TestData class, depends on the data used by your application.

Also, you may want some of the methods to take parameters, rather than e.g. always inserting a hardcoded customer, or product etc.

Using the TestData Class

Once you have such a TestData class, you can use and reuse it in your unit tests. The TestData class can contain all kinds of business wise complex test data setups, which are then easy to setup in the database, once they have been programmed once.

Here is a very simple usage example:


@Test
public void testIt() {
  TestData testData = getTestDataInstance(); // get this from somewhere...

  testData.setupCustomerSituation();

  MyOperation operation = new MyOperation();

  operation.doIt();

  assertTrue(...);
  //etc.

}    

Advantages of a TestData Class

The two main advantages of a TestData class are:

  • Test data creation can be reused.
  • The TestData class can be documented, so each test case can explain what data (business situation) it sets up.

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