DbUnit Express Tips: Setup Simplification, Custom Data File Convention

I've recently introduced here DbUnit Express, a wrapper around DbUnit intended to get you started with testing DB-related code in no time, and now I'd like to share two productivity tips: simplifying db tester setup with a parent test and implementing your own convention for data set files, for example one data set per test class.

Define your own convention for data set names, e.g. per-test-class-data-set

By default DbUnit Express expects you to use dataset testData/dbunit-test_data_set.xml. However you might for example prefer each test to have its own data set, named for example <test class name>-test.xml.

The easiest solution without repeating yourself is to create a custom subclass of EmbeddedDbTester overriding its createDefaultDataSet():


public class PerTestDataSetEmbeddedDbTester extends EmbeddedDbTester {
    @Override
    protected IDataSet createDefaultDataSet() throws DatabaseUnitRuntimeException, DataSetException {
		return createDataSetFromFile(getClass().getSimpleName() + "-data.xml");
	}
}


Notice that if the data set cannot be found in the default location, i.e. testData/, then it is searched for on the classpath, so it is perfectly OK to have it next to the test class.

Setup Simplification

When using DbUnit Express with JUnit 4.x, you typically need to do three things in each test class:


public class SpringBookDaoImplTest {

private EmbeddedDbTester testDb = new EmbeddedDbTester(); // 1

@Before public void setUp() throws Exception { testDb.onSetup(); // 2 }

@After public void tearDown() throws Exception { testDb.onTearDown(); // 3 }

... }


That is lot of repeated coding and the best way to get rid of it is to create an abstract parent class of all your test classes working with DbUnit Express and moving the code there (changing the tester's visibility to protected, of course):


public abstract class AbstractMyApplicationDbTest {

protected EmbeddedDbTester testDb = new EmbeddedDbTester(); // 1

@Before public final void setUpDbUnitExpress() throws Exception { testDb.onSetup(); // 2 }

@After public final void tearDownDbUnitExpress() throws Exception { testDb.onTearDown(); // 3 }

... }

Tags: java library


Copyright © 2024 Jakub Holý
Powered by Cryogen
Theme by KingMob