Integration testing with DbUnit and Spring framework

In the previous post, I gave a short example how to run the integration test with Spring framework. In this post, I share the example how to do the database testing with DbUnit. The primary principle of the unit test is separating data in the each test case, and DbUnit helps us keep data in every integration testing in a known state. We enhance JUnit, Spring framework to add the rule of running DbUnit at the beginning and during every test case.

Adding the Maven dependencies

We add the DbUnit to the Maven file (From the previous post, we added the Spring, and JUnit already). I suggest using the testing toolkit assertj while it is very helpful for your development team by providing the rich set of assertions, helpful error messages and make you focus on testing code.

Creating the DbUnit rule for JUnit

We will write the JUnit rule for DbUnit to run the DbUnit setup task in every test case. This rule will clean the database tables, load the test data in XML file and insert into the database.

You can read the full source code of DbUnitInitializerRule at here.

Write the test data

The test data in the XML format. For an example, we name the file is AccountServiceTest.xml

Write the JUnit test case

First of all, we created the parent class for all database integration test cases

and then create the test case AccountServiceTest

By the rule of DbUnitInitializerRule, the class AccountServiceTest and the XML data file AccountServiceTest.xml must be in the same package.

The annotation @DataSet is our custom annotation to ask JUnit rule DbUnitInitializerRule to initialize the DbUnit process. We also use the assertions of assertj to keep our unit test readable, which is extremely useful to assert data in the collection.

To keep our code quality, we wrote a lot of test cases: unit test, database testing and integration testing with the mock object. To illustrate this post, we share several database testing in the MyCollab github folder.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *