Unit testing the database layer

Testing the database layer. Usually an important part of many applications and thus everyone should test it.

But how do you do that?
(if you know how it’s done, this post is not for you, go read something more interesting then!)

You don’t want to setup an Oracle, MySQL, PostgreSQL and such just for running unit tests. Your option? Use an in memory database!

There are a couple of tools available on the opensource market to test your dao layer. I’ve put together an example for a database layer that is using Spring 3.1.2 with JPA2/Hibernate 4.x. For testing I choose the combination of Unitils, H2 in memory database and JUnit.

Unitils is the thing that creates the database using your entities or if you want it can also create your database using an sql script. I usually let hibernate create the database. And add some <dataset> xmls with data.

You can find the example code at github.

Take a look at the tests in src/test/java to see how it is done. There is one test that uses an xml file to populate the database and another test without an xml file. I’ve added Javadoc to the tests to explain what is happening.

This way of testing also allows you to test your service layer with a predefined dataset. Personally I prefer to mock stuff in the service layers. But for doing integration tests it can be useful to have an in memory database.

Happy Testing!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: