DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Inner Loop Is Eating The Outer Loop
  • Doris Lakehouse Integration: A New Approach to Data Analysis
  • Mocking and Its Importance in Integration and E2E Testing
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3

Trending

  • The "Just Read the Code" Myth Is Killing Your AI Workflow
  • Using the Anthropic Evaluation Tool to Check the Claude Code Plugin Efficiency
  • Managing Technical Debt in AI-Generated Code
  • Designing a Polling Pipeline for Rate-Limited APIs Without Losing Data

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Easy Integration Testing with Spring+Hibernate

Easy Integration Testing with Spring+Hibernate

By 
Dinuka Arseculeratne
·
Nov. 27, 12 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
56.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

 I am guilty of not writing integration testing (At least for database related transactions) up until now. So in order to eradicate the guilt i read up on how one can achieve this with minimal effort during the weekend. Came up with a small example depicting how to achieve this with ease using Spring and Hibernate. With integration testing, you can test your DAO(Data access object) layer without ever having to deploy the application. For me this is a huge plus since now i can even test my criteria's, named queries and the sort without having to run the application.

There is a property in hibernate that allows you to specify an sql script to run when the Session factory is initialized. With this, i can now populate tables with data that required by my DAO layer. The property is as follows;

    <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>  

According to the hibernate documentation, you can have many comma separated sql scripts.One gotcha here is that you cannot create tables using the script. Because the schema needs to be created first in order for the script to run. Even if you issue a create table statement within the script, this is ignored when executing the script as i saw it.

Let me first show you the DAO class i am going to test;

     package com.unittest.session.example1.dao;  
      
    import org.springframework.transaction.annotation.Propagation;  
    import org.springframework.transaction.annotation.Transactional;  
      
    import com.unittest.session.example1.domain.Employee;  
      
    @Transactional(propagation = Propagation.REQUIRED)  
    public interface EmployeeDAO {  
      
     public Long createEmployee(Employee emp);  
       
     public Employee getEmployeeById(Long id);  
    }  

    package com.unittest.session.example1.dao.hibernate;  
      
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
      
    import com.unittest.session.example1.dao.EmployeeDAO;  
    import com.unittest.session.example1.domain.Employee;  
      
    public class EmployeeHibernateDAOImpl extends HibernateDaoSupport implements  
      EmployeeDAO {  
      
     @Override  
     public Long createEmployee(Employee emp) {  
      getHibernateTemplate().persist(emp);  
      return emp.getEmpId();  
     }  
      
     public Employee getEmployeeById(Long id) {  
      return getHibernateTemplate().get(Employee.class, id);  
     }  
    }  

Nothing major, just a simple DAO with two methods where one is to persist and one is to retrieve. For me to test the retrieval method i need to populate the Employee table with some data. This is where the import sql script which was explained before comes into play. The import.sql file is as follows;

    insert into Employee (empId,emp_name) values (1,'Emp test');  

This is just a basic script in which i am inserting one record to the employee table. Note again here that the employee table should be created through the hibernate auto create DDL option in order for the sql script to run. More info can be found here. Also the import.sql script in my instance is within the classpath. This is required in order for it to be picked up to be executed when the Session factory is created.

Next up let us see how easy it is to run integration tests with Spring.

     package com.unittest.session.example1.dao.hibernate;  
      
    import static org.junit.Assert.*;  
      
    import org.junit.Test;  
    import org.junit.runner.RunWith;  
    import org.springframework.beans.factory.annotation.Autowired;  
    import org.springframework.test.context.ContextConfiguration;  
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
    import org.springframework.test.context.transaction.TransactionConfiguration;  
      
    import com.unittest.session.example1.dao.EmployeeDAO;  
    import com.unittest.session.example1.domain.Employee;  
      
    @RunWith(SpringJUnit4ClassRunner.class)  
    @ContextConfiguration(locations="classpath:spring-context.xml")  
    @TransactionConfiguration(defaultRollback=true,transactionManager="transactionManager")  
    public class EmployeeHibernateDAOImplTest {  
      
     @Autowired  
     private EmployeeDAO employeeDAO;  
       
     @Test  
     public void testGetEmployeeById() {  
      Employee emp = employeeDAO.getEmployeeById(1L);  
        
      assertNotNull(emp);  
     }  
       
     @Test  
     public void testCreateEmployee()  
     {  
      Employee emp = new Employee();  
      emp.setName("Emp123");  
      Long key = employeeDAO.createEmployee(emp);  
        
      assertEquals(2L, key.longValue());  
     }  
      
    }  

A few things to note here is that you need to instruct to run the test within a Spring context. We use the SpringJUnit4ClassRunner for this. Also the transction attribute is set to defaultRollback=true. Note that with MySQL, for this to work, your tables must have the InnoDB engine set as the MyISAM engine does not support transactions.

And finally i present the spring configuration which wires everything up;

     <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
     xsi:schemaLocation="    
              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd    
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd    
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd    
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
      
      
     <context:component-scan base-package="com.unittest.session.example1" />  
     <context:annotation-config />  
      
     <tx:annotation-driven />  
      
     <bean id="sessionFactory"  
      class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
      <property name="packagesToScan">  
       <list>  
        <value>com.unittest.session.example1.**.*</value>  
       </list>  
      </property>  
      <property name="hibernateProperties">  
       <props>  
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
        <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>  
        <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/hbmex1</prop>  
        <prop key="hibernate.connection.username">root</prop>  
        <prop key="hibernate.connection.password">password</prop>  
        <prop key="hibernate.show_sql">true</prop>  
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
        <!-- -->  
        <prop key="hibernate.hbm2ddl.auto">create</prop>  
        <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>  
       </props>  
      </property>  
     </bean>  
      
     <bean id="empDAO"  
      class="com.unittest.session.example1.dao.hibernate.EmployeeHibernateDAOImpl">  
      <property name="sessionFactory" ref="sessionFactory" />  
     </bean>  
      
     <bean id="transactionManager"  
      class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
      <property name="sessionFactory" ref="sessionFactory" />  
     </bean>  
      
    </beans>  

That is about it. Personally i would much rather use a more light weight in-memory database such as hsqldb in order to run my integration tests.

Here is the eclipse project for anyone who would like to run the program and try it out.

Integration testing Database Integration

Published at DZone with permission of Dinuka Arseculeratne. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Inner Loop Is Eating The Outer Loop
  • Doris Lakehouse Integration: A New Approach to Data Analysis
  • Mocking and Its Importance in Integration and E2E Testing
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook