Easy Integration Testing with Spring+Hibernate

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介:

原文地址:http://architects.dzone.com/articles/easy-integration-testing

 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);  

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 theSpringJUnit4ClassRunner for this. Also the transction attribute is set to defaultRollback=true. Note that withMySQL, 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/contexthttp://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 ashsqldb 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.

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
1月前
|
XML JSON Java
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
本文介绍了如何使用IntelliJ IDEA和Maven搭建一个整合了Struts2、Spring4、Hibernate4的J2EE项目,并配置了项目目录结构、web.xml、welcome.jsp以及多个JSP页面,用于刷新和学习传统的SSH框架。
32 0
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
|
27天前
|
Java Spring
【Azure Service Bus】使用Spring Cloud integration示例代码,为多个 Service Bus的连接使用 ConnectionString 方式
【Azure Service Bus】使用Spring Cloud integration示例代码,为多个 Service Bus的连接使用 ConnectionString 方式
|
30天前
|
Java 数据库连接 数据库
Spring Data JPA 与 Hibernate 之区别
【8月更文挑战第21天】
17 0
|
3月前
|
消息中间件 监控 Java
Java一分钟之-Spring Integration:企业级集成
【6月更文挑战第11天】Spring Integration是Spring框架的一部分,用于简化企业应用的集成,基于EIP设计,采用消息传递连接不同服务。核心概念包括通道(Channel)、端点(Endpoint)和适配器(Adapter)。常见问题涉及过度设计、消息丢失与重复处理、性能瓶颈。解决策略包括遵循YAGNI原则、使用幂等性和事务管理、优化线程配置。通过添加依赖并创建简单消息处理链,可以开始使用Spring Integration。注意实践中要关注消息可靠性、系统性能,逐步探索高级特性以提升集成解决方案的质量和可维护性。
62 3
Java一分钟之-Spring Integration:企业级集成
|
2月前
|
Java 数据库连接 数据库
如何在Spring Boot中集成Hibernate
如何在Spring Boot中集成Hibernate
|
3月前
|
前端开发 Java 关系型数据库
在Spring3 MVC中五步配置集成注解方式Hibernate3
在Spring3 MVC中五步配置集成注解方式Hibernate3
37 3
|
3月前
|
XML Java Apache
必知的技术知识:HHS整合(Struts2+Spring+Hibernate)
必知的技术知识:HHS整合(Struts2+Spring+Hibernate)
27 0
|
4月前
|
SQL Java 数据库连接
jpa、hibernate、spring-data-jpa、jdbcTemplate
jpa、hibernate、spring-data-jpa、jdbcTemplate
|
4月前
|
Java 数据库连接 Spring
spring配合hibernate报错:sessionFactory or hibernateTemplate is required
根据你的具体情况,检查上述步骤中的一个或多个,以确定为何出现“sessionFactory or hibernateTemplate is required”错误,并采取相应的措施进行修复。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
29 0
|
4月前
|
网络安全
ssh(Spring+Spring mvc+hibernate)——updateEmp.jsp
ssh(Spring+Spring mvc+hibernate)——updateEmp.jsp