Having Database Test Ready in 10 Minutes with DbUnit Express

Update: The project has been renamed to dbunit-express.

DbUnit Express is my wrapper around DbUnit that intends to make it extremely easy to set up a test of a code that interacts with a database. It is preconfigured to use an embedded Derby database (a.k.a. JavaDB, part of SDK) and uses convention over configuration to find the test data. It can also with one call create the test DB from a .ddl file. Aside of simplifying the setup it contains few utilities to make testing easier such as getDataSource() (essential for testing Spring JDBC) and RowComparator.

Originally I was using DbUnit directly but I found out that for every project I was copying lot of code and thus I decided to extract it into a reusable project. Since that it has further grown to be more flexible and make testing even easier.

Here are the seven easy steps to have a running database test:
  1. Add binaries: Add dbunit-embeddedderby-parenttest 1.2.0 to your dependencies (note: it has been renamed to dbunit-express in later versions)
    
    <dependency>
     	<groupId>net.jakubholy.testing</groupId>
    	<artifactId>dbunit-embeddedderby-parenttest</artifactId>
    	<version>1.2.0</version>
    	<scope>test</scope>
    </dependency>

    <dependency> <!-- won't be required in future versions --> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.5.6</version> <scope>test</scope> </dependency>
  2. Create the folder testData/ under your project's root folder.
  3. (optional) Prepare .ddl: Copy the example testData/create_db_content.ddl into the new testData/ and modify it to fit your data schema needs
  4. (optional) Create & initialize DB: Run DatabaseCreator#main from your project's root folder to create and initialize the test DB from the .ddl file.
  5. Write a TestCase: Either subclass AbstractEmbeddedDbTestCase or create and use an instance of EmbeddedDbTester in your test class and implement your tests there. (See SimpleEmbeddedDbTest.java and SimpleNonExtendingEmbeddedDbTest.java for inspiration.) You may want to override its getDataSet() if you want to use st. else than the default testData/dbunit-test_data_set.xml.
  6. Prepare test data: Copy the example testData/dbunit-test_data_set.xml into your new testData/ and modify it to fit your data needs. Any table mentioned in the file will be emptied prior to running test, if it has any rows defined than those will be also inserted
    • You may use e.g. Jailer (good tutorial) to produce a subset of your database in DbUnit XML format (unfortunately only Flat XML) or another tool supporting it such as QuantumDB.
  7. Run the test.
You may read more about DbUnit Express on its home page.

PS: The last released version 1.2.0 is from 4/2010, a new version should be out in few weeks.

Tags: testing java


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