Home > Uncategorized > Workaround for DBUnit

Workaround for DBUnit

March 8th, 2005

DBUnit has an odd requirement for tables used for testing: Each table must have a primary key defined. If you don’t have a primary key for a given table when you’re loading data, you’ll get an exception. To work around this exception, you have to create your own implementation of DBUnits IColumnFilter interface and register it. The following code listing has a trivial implementation of the interface:

public class MyColumnFilter implements IColumnFilter {
public boolean accept(String tableName, Column column) {
// since my seating_links table doesn’t have a primary key,
// just return true;
if (tableName != null && tableName.equals(”seating_links”)) {
return true;
}
else {
if (column.getName().equals(”id”)) {
return true;
}
else {
return false;
}
}
}
}

With the implementation done, we just need to tell DBUnit to use it:

IDatabaseConnection conn = new DatabaseConnection(jdbcConn);
conn.getConfig().setProperty(
“http://www.dbunit.org/properties/primaryKeyFilter”,
new MyColumnFilter());

This is a little long-winded for something that should be trivial. However, I have this code in my base test case class so I don’t need to duplicate it throughout the test code.

nick Uncategorized

Comments are closed.