Having Database Tests Ready in 10 Minutes with 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:
- Add binaries: Add dbunit-embeddedderby-parenttest 1.2.0 to your dependencies (note: in future versions it will be renamed to dbunit-express)
<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>
- Create the folder testData/ under your project’s root folder.
- (optional) Prepare .ddl: Copy the example testData/create_db_content.ddl into the new testData/ and modify it to fit your data schema needs
- (optional) Create & initialize DB: Run DatabaseCreator#main from your project’s root folder to create and initialize the test DB from the .ddl file.
- 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.
- 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
- Run the test.
PS: The last released version 1.2.0 is from 4/2010, a new version should be out in few weeks.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)