Phil Webb's Blog

Random thoughts from a software developer

Archive for the ‘DBUnit’ Category

Database testing using DBUnit, Spring and Annotations

with 31 comments

If you have ever tried writing database tests in Java you might have come across DBUnit. DBUnit allows you to setup and teardown your database so that it contains consistent rows that you can write tests against. You usually specify the rows that you want DBUnit to insert by writing a simple XML document, for example:

<?xml version="1.0" encoding="UTF-8"?>
	<Person id="0" title="Mr" firstName="Dave" lastName="Smith"/>
	<Person id="1" title="Mrs" firstName="Jane" lastName="Doe"/>

You can also use the same format XML files to assert that a database contains specific rows.

DBUnit works especially well using in-memory databases, and if you work with Spring, setting them up is pretty straightforward. Here is a good article describing how to get started.

Working directly with DBUnit is fine, but after a while it can become apparent how many of your tests are following the same pattern of setting-up the database then testing the result. To cut down on this duplication you can use the spring-test-dbunit project. This project is hosted on GitHub and provides a new set of annotations that can be added to your test methods. Version 1.0.0 has just been released and is now available in the maven central repository:


Once installed three new annotations are available for use in your tests: @DatabaseSetup, @DatabaseTearDown and @ExpectedDatabase. All three can either be used on the test class or individual test methods.

The @DatabaseSetup and @DatabaseTearDown annotations are used to put your database into a consistent state, either before the test runs or after it has finished. You specify the dataset to use as the annotation value, for example:

public void testFind() throws Exception {
  // test code

The @ExpectedDatabase annotation is used to verify the state of the database after the test has finished. As with the previous annotations you must specify the dataset to use.

public void testRemove() throws Exception {
  // test code

You can use @ExpectedDatabase in a couple of different modes depending on how strict the verification should be (see the JavaDocs for details).

For the annotations to be processed you need to make sure that your test is using the DbUnitTestExecutionListener. See the project readme for full details. If you want to learn more there is an example project on GitHub and some walk-though instructions available here.


Written by Phillip Webb

April 23, 2012 at 12:52 am

Posted in DBUnit, Spring