Home > Solutions Log > Running database tests faster using TestNG

Running database tests faster using TestNG

In a recent project, I was doing some integration testing against database using DBUnit and JUnit. I was dealing with large datasets and as the tests grew, testing became painfully slow. Culprit: I had JUnit update the database with data for every test.

The data access layer for this project had lots of complex queries but the methods I was testing had two distinct behaviors: methods that read data from the database and methods that wrote data to the database. This simple observation made me realize that I can cut down the testing time by 
  – Grouping tests in to “read” and “write” groups
  – Refreshing database and run ALL the tests in the “read” group (even better run them parallely)
  – Refreshing database before running each and every test in the “write” group

Since JUnit does not provide a way to implement the above idea, I tried TestNG. Here is a simple java code of what I ended up doing:


public class RepositoryImplTest {
  
  private void setupDataBase() {
    // DBUnit code to refresh data
  }
  
  @BeforeClass(groups={"database.read"}, alwaysRun=false)
  public void setupForRead() {
    setupDataBase();
  }
  
  @BeforeMethod(groups={"database.write"}, alwaysRun=false)
  public void setupForWrite() {
    setupDataBase();
  }
  
  @Test(groups="database.read")
  public void findAllXXX() {
    
  }
  
  @Test(groups="database.read")
  public void findByXXX() {
    
  }
  
  @Test(groups="database.write")
  public void updateXXX() {
    
  }
  
  @Test(groups="database.write")
  public void removeXXX() {
    
  }  
  
  @Test(groups="database.write")
  public void createXXX() {
    
  }
}

Here is the sample testng.xml file for the above code:

Categories: Solutions Log Tags:
  1. No comments yet.
  1. No trackbacks yet.