原文地址: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 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 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.
新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。
价格最低购买地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail
或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。
相关推荐
Struts、Spring 和 Hibernate...总的来说,这个"Struts+Spring+Hibernate实现的增删查Demo"提供了一个学习和实践企业级Java Web开发的平台,通过实际操作,开发者可以深入理解这三大框架的协同工作原理,提升开发技能。
这个压缩包"jquery easy UI+spring3.0+struts2.1.8.1+hibernate3.5整合的CRM包括所有Jar包"提供了一种基于Java的技术栈,用于构建客户关系管理(CRM)系统。下面将详细介绍这些组件以及它们之间的整合方式。 首先,...
"StudentSystem easy UI struts2+hibernate+spring实现"是一个典型的企业级应用实例,它巧妙地融合了三个流行的技术框架:Struts2、Hibernate和Spring,构建出一个易于使用的用户界面。这个项目的核心目标是提供一个...
spring-framework-5.1.9.RELEASE-dist,Struts-2.5.20-all,hibernate-release-5.3.11.Final库包 commons-logging-1.2.jar,免费分享给大家了!
5:easy ui 1.5,hibernate用的是3的版本 本系统是整合了ssh框架的一个简单的图书管理系统,功能集合了,读者、管理员、书籍、书架、街还书信息等的增删改查,读者具备注册账号,设置账号密保,账号找回、书籍信息...
简单的JSF+Hibernate+Spring集成项目 This project is very easy to understand JSF,Spring and Hibernate integration.项目结构 如果你想使用这个项目。你几乎不需要改变。 1.Go to WEB-INF/applicationContext.xml...
Easy+Touch+5+Touchscreen+Virtual+Controls+5.0.12.unitypackage
easy-flow 基于VUE+ElementUI+JsPlumb的流程设计器,通过 vuedraggable 插件来实现节点拖拽。支持拖拽添加节点,点击线进行设置条件,支持给定数据加载流程图,支持画布拖拽,支持连线样式、锚点、类型自定义覆盖,...
一键ROOT工具+Easy+Rooting+Toolkit+v2.0.zip
Manning出版 Java Persistence With Hibernate 第二版 清晰pdf Hibernate, an open source project that is almost 15 years old. In a recent poll, Hibernate was among the top five tools used by many Java ...
Brian Okken takes the trouble to show that software testing with pytest is easy, natural, and even exciting. ➤ Dmitry Zinoviev Author of Data Science Essentials in Python This book is the missing ...
在压缩包文件"Easy+Touch+5+TouchscreenC.unitypackage"中,包含了Easy Touch 5的所有核心资源和脚本,导入到Unity项目后,开发者可以立即开始使用。只需按照指导将相应的组件添加到游戏对象上,然后通过脚本配置...
"Easy+Touch+5+Touchscreen+Virtual+Controls+5.0.17.unitypackage"文件包含了这个插件的所有组件,开发者只需将其导入到Unity项目中,即可开始使用EasyTouch和EasyTouchControls的功能。 使用这个插件时,开发者...
to relational and NoSQL datastores, batch processing, integration with social networking sites, large volume of data streams processing, etc. As Spring is a very flexible and customizable framework, ...
【EasyUEFI 3.1 Enterprise】是一款专为企业用户设计的EFI系统分区管理工具,它提供了全面、便捷的方式来管理和维护EFI(Extensible Firmware Interface)启动选项。EFI是现代计算机BIOS的一种替代方案,特别是在...
《Unity中的Easy Movie Texture与Video Texture:实现动态视频纹理的3.20版本解析》 在Unity游戏引擎中,动态视频纹理是制作交互式游戏、虚拟现实应用等项目时非常重要的一个元素。Easy Movie Texture与Video ...
### 案例8:Spring整合Spring MVC与Hibernate + EasyUI实现电子商城后台订单管理 #### 一、项目概述 本案例旨在通过整合Spring、Spring MVC、Hibernate以及EasyUI技术框架,实现一个功能完整的电子商城后台订单...