Integration Testing with DB Unit

First checkout DB Unit:

DbUnit is a JUnit extension targeted at database-driven projects that, among other things, puts your database into a known state between test runs.
DbUnit has the ability to export and import your database data to and from XML datasets.
DbUnit can also help you to verify that your database data match an expected set of values

Add dependencies:


Export XML dataset:

  @Autowired private DataSource dataSource;

  public void export() throws Exception{
        IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());
        IDataSet fullDataSet = connection.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));

Configure and use a DatabaseTester (since we use a DataSource we can pick DataSourceDatabaseTester):

DataSourceDatabaseTester tester = new DataSourceDatabaseTester(dataSource);
tester.onSetup(); // restores database !

To restore before each test place the above inside a @Before annotated method.

Finally the JUnit class should extend DataSourceBasedDBTestCase, simply implement:

DataSource getDataSource()
IDataSet getDataSet(

Ready to Test !
Note: Might have to turn off foreign key constraints on data source:

Tagged with: , , ,
Posted in Database, JUnit, Testing

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: