Monday, March 24, 2014

DBunit table record counting

During unit testing is useful to verify that requested operation was really performed in db. Lets have a simple test for deleting method. This method just delete user record in database. Test could look like:

public void testDelete() throws Exception{
 userDao.delete(5);
 restartSession();
 
 assertEquals(getConnection().createDataSet().getTable("user").getRowCount(),
  getDataSet().getTable("user").getRowCount() - 1);
}

This test look clear. however there is possible problem. Running this code could ends with exception:

org.dbunit.database.AmbiguousTableNameException: user
 at org.dbunit.dataset.AbstractDataSet.getTable(AbstractDataSet.java:101)
 at org.dbunit.dataset.ReplacementDataSet.getTable(ReplacementDataSet.java:182)
 ...

When you look at exception source problem is clear. The problem are testing data. When you have testing data in XML file in following shape:

 <user id_user="3" login_name="john" user_name="John" password="e"
  public_profile="1" app_right="1" />

 <color id_color="1" />
 <color id_color="2" />

 <user id_user="5" login_name="clara" user_name="Clara" password="e"
  public_profile="1" app_right="1" />

Thank DBunit took it as two table user definition. Each definition have it's own list of rows with data. So solution is obvious, just re-order data definition XML file.
 <user id_user="3" login_name="john" user_name="John" password="e"
  public_profile="1" app_right="1" />
 <user id_user="5" login_name="clara" user_name="Clara" password="e"
  public_profile="1" app_right="1" />

 <color id_color="1" />
 <color id_color="2" />

No comments:

Post a Comment