Archive for May, 2014

How to unit test Hibernate DAO’s with H2 and Spring

May 12, 2014 Comments off

Source can be downloaded from link;

Writing Unit test cases are very common these days.We can write a Unit test for the functionality with Mocking.I personally feel we should not do Mocking while testing DAO.I prefer to write test cases for the DAO’s by pointing to the Database itself.Here the problem is we cannot execute tests on the production or development database since it will spoil the existing data, because we can build the same project any number of time, especially when we configure continues integration.

In memory databases or file based database comes in handy in this particular situation.There are lot many databases available of this kind like h2, HSQLDB e.t.c.

Here below i have extended a sample created in the below post and have written unit test with h2 database.

Link :

Project Structure



Create a test class with the similar package structure as source class in src/test/java


Sample Insert.sql below.


Sample delete.sql below


Now the main part come into the picture.applicationcontext.xml

We need to configure the h2 database data source as per below.


and the Session Factory as per below.


and we have to add spring-test dependency to the pom file.


Categories: H2, Hibernate, Java, Maven, Spring Tags:
%d bloggers like this: