DbUnit is a JUnit extension and is very popular among developers for unit testing database-driven projects. In this blog I will discuss some of the tips to make your life easier and beautiful for DbUnit testing.

Using same connection for entire test suite
If you are extending DatabaseTestCase then this class creates a connection to the database in setUp() and closes it in teardown() this can prove to be a big overhead and can cause considerable slowdown in running tests as the number of test cases increase. Maintaining a single connection for the entire test suite can prove to be beneficial in such cases.

If you are using JUnit 4 then you can use annotations for performing initial operations (@BeforeClass) and thus there is no need to extend the DatabaseTestCase and finally handling the closing of database connection.

public static void setUpBeforeClass() throws Exception {
If several test cases are using a read only dataset as expected state of the database after running the test cases then loading this expected dataset file only once for all the test cases can help up in speeding up things.

Specifying a DTD for the dataset can act as a cure for some of the things
You can create a DTD by using the following code in DbUnit.

new FileOutputStream(“test.dtd”)); [/java]

This DTD can be used now to
– Validate a dataset file against it.
– Providing null values to a column by omitting it for a row in dataset.

Keeping some reusable methods
A few reusable methods like asserting the database state after running tests with an expected state dataset file can be very useful. I am mentioning one of such methods here
[java] protected void assertTables(String filename, String[] tableNames)
throws SQLException, Exception, DataSetException, IOException,
DatabaseUnitException {
IDataSet expectedDataSet = null;
if (tableNames == null) {
// Load expected data from an XML data set
expectedDataSet = new FlatXmlDataSet(new File(filename));
tableNames = expectedDataSet.getTableNames();
} else {
// Load subset of the complete dataset
expectedDataSet = new FilteredDataSet(tableNames,
new FlatXmlDataSet(new File(filename)));
// Fetch database data after executing your code
IDataSet actualDataSet = getConnection().createDataSet(tableNames);
ITable[] expectedTables = new CompositeTable[tableNames.length];
for (int i = 0; i Happy Red-Green-Refactor-ing.