DBUnit is a very good tool for use in testing Hibernate applications in the data access layer. DBUnit based tests work by comparing the state of the database from particular method calls and comparing with an expected data set. If the data sets match with the database data state, then the test is said to be successful.

Fortunately, using DBunit is straightforward and powerful tests and comparisons can be done.

Setting up DBUnit to use in unit tests

In Maven POM, add the DBUnit dependency as follows:

        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.4.7</version>
            <scope>test</scope>
        </dependency>

For ANT or if using manually, then add the JAR to the test classpath. DBUnit is now ready to be used in tests.

When writing tests, the unit test class must now extend the abstract class org.dbunit.DatabaseTestCase and implement the two key methods which are:

1) getConnection – retrieves the database connection to perform the unit tests via DBUnit

2) getDataSet – retrieves a dataset to be manipulated either from a table or flat file that can be in XML format.

 

            <version>2.4.7</version>