`
wiselyman
  • 浏览: 2080864 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
博客专栏
Group-logo
点睛Spring4.1
浏览量:81077
74ae1471-94c5-3ae2-b227-779326b57435
点睛Spring MVC4...
浏览量:130130
社区版块
存档分类
最新评论

Easy Integration Testing with Spring+Hibernate

 
阅读更多

原文地址: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

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


分享到:
评论

相关推荐

    通信电源蓄电池组容量性充放电试验三措一案.docx

    5G通信行业、网络优化、通信工程建设资料。

    铁塔维护检测手段.docx

    5G通信行业、网络优化、通信工程建设资料

    通信设备安装施工组织方案.doc

    5G通信、网络优化与通信建设

    299-教育行业信息化与数据平台建设分享.pptx

    299-教育行业信息化与数据平台建设分享.pptx

    手写数字和字母数据集binaryalphadigs.mat

    手写数字和字母数据集binaryalphadigs.mat

    变电站视频监控解决方案.doc

    5G通信行业、网络优化、通信工程建设资料

    PEMFC电堆输出电压模型,可计算效率、输出功率、电流、消耗功率以及等效内阻

    PEMFC电堆输出电压模型,可计算效率、输出功率、电流、消耗功率以及等效内阻

    创建型 结构型 设计型设计模式相关知识

    1、 设计思路 1、 创建型设计模式 创建型设计模式主要“关注对象的创建”。 1. 单例模式 单例模式:能不用就不用 ,他的目的就是为了让一个类只创建一个实例。 用法:把对象的创建权限关闭,提供一个人公开的静态方法,实现静态方法后将实例存放于静态的字段中,方法中返回。 单例模式会长期持有一个对象不会被释放,而普通实例不用就会被释放(当然必须是GC之后才会被释放)。 单例用途;数据临时存储的地方如静态字典,数据库连接池、线程池、IOC容器实例。   1.1懒汉式 设置构造函数为私有的,避免其他外部类可以对其实例化, 创建静态类来存储实例。 在静态方法中创建实例,避免多个线程同时调用方法,我们可以加线程锁, 在方法中使用双判断语句:最外层判断是为了提高运行速率,检查如果静态字段中已经存在实例了就可以直接return;第二层判断是避免创建多个对象实例。 1.2饿汉式1 静态构造函数:由CLR保证,静态构造函数只会在启动程序时候,由CLR自行创建。并且只会创建一次,相比较于懒汉式创建的更早,并且不需要担心会

    《通信工程概预算》模拟试题2.docx

    5G通信行业、网络优化、通信工程建设资料

    毕业设计:Java项目之jsp高校规章制度管理系统(源码 + 数据库 + 说明文档)

    论文目录: 第二章 需求分析与系统总体设计 - 5 - 2.1java的特点 - 5 - 2.2技术可行性 - 5 - 2.3可靠性和安全性特点 - 6 - 2.4系统总体设计 - 6 - 2.5JSP技术介绍 - 7 - 2.5.1 什么是JSP - 7 - 2.5.2 JSP技术特点 - 7 - 2.5.3 JSP开发WEB的几种方式 - 8 - 第三章 数据库的设计与实现 - 9 - 3.1数据库的需求分析 - 9 - 3.2数据库的逻辑设计 - 10 - 3.3 数据库的结构创建 - 10 - 第四章 后台系统和数据库的配置 - 13 - 4.1后台服务器配置 - 13 - 4.2后台数据库的配置 - 13 - 4.3后台全局配置文件 - 13 - 第五章 前端网络页面的开发与设计 - 14 - 5.1登录页面 - 14 - 5.2 管理员用户页面 - 15 - 5.3 注册用户页面 - 16 - 5.4主页面 - 17 - 5.5用户注册页面 - 18 - 5.6 规章制度管理页面 - 18 - 第六章 系统的安全性 - 19 - 6.1 session和cookie的安

    ONU、分光器验收规范.doc

    5G通信行业、网络优化、通信工程建设资料。

    99-煤矿安全生产标准化基本要求及评分方法.pdf

    99-煤矿安全生产标准化基本要求及评分方法.pdf

    node-v12.22.6-sunos-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    475现场通讯器用户手册

    475现场通讯器用户手册

    node-v7.7.0.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    600A钳形电流表使用手册

    600A钳形电流表使用手册

    常见宏基站认识和设计讲解.pptx

    5G通信、网络优化与通信建设

    node-v12.16.3-sunos-x64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    数据中心机房供电需求分析.pptx

    5G通信、网络优化与通信建设

    Binomial Self-compensation

    Binomial Self-compensation for Motion Error in Dynamic 3D Scanning

Global site tag (gtag.js) - Google Analytics