Archive

Archive for the ‘Spring’ Category

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 : http://examples.javacodegeeks.com/enterprise-java/spring/jpaorm/spring-hibernate-mysql-and-maven-showcase/

Project Structure

Image

 

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

Image

Sample Insert.sql below.

Image

Sample delete.sql below

Image

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

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

Image

and the Session Factory as per below.

Image

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

Image

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