资源准备:   mysql5.0 spring-2.5  hibernate-3.2  junit-4.jar

创建表

DROP TABLE IF EXISTS `myproject`.`boys`;
CREATE TABLE `myproject`.`boys` (
`id` bigint(20) NOT NULL auto_increment,
`phone` varchar(20) default NULL,
`sex` varchar(2) default NULL,
`address` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建相关配置文件:

(1)applicationContext-resources.xml

<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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"> <!--
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- =====使用dbcp 连接池 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:mappingResources="testHibernate.hbm.xml">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">
${hibernate.show_sql}
</prop>
<!--<prop key="hibernate.generate_statistics">
${hibernate.generate_statistics}
</prop>
-->
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<!-- 所有抛出异常都要回滚 -->
<tx:method name="*" rollback-for="Throwable" />
</tx:attributes>
</tx:advice> <!-- com.jmesa.test.service包下面(包括子包)后缀为Service的所有bean -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.jmesa.test.service..*Service.*(..))" />
<aop:advisor pointcut-ref="serviceOperation"
advice-ref="txAdvice"/>
</aop:config>
</beans>

(2) applicationContext-dao.xml

<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee htp://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean name="boysDAO" class="com.jmesa.test.dao.hibernate.BoysDAOImpl" autowire="byName"></bean>
</beans>

(3)jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/myproject?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true

(4) boys 实体的hibernate配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping auto-import="true" default-lazy="false">
<class name="com.jmesa.test.model.Boy" table="boys">
<id name="id" column="id" type="long">
<generator class="identity"></generator>
</id>
<property name="phone" column="phone"></property>
<property name="sex" column="sex"></property>
<property name="address"></property>
</class>
</hibernate-mapping>

(5)创建BoysDAO 接口

package com.jmesa.test.dao;

import java.util.List;

import com.jmesa.test.common.EntityFilters;
import com.jmesa.test.common.EntitySorts;
import com.jmesa.test.model.Boy; public interface BoysDAO {
/**
*
* @param boy
* 域对象
*/
public void save(Boy boy); /**
* 更新boy数据
*
* @param boy
*/
public void update(Boy boy); /**
* 依据id值获得boy域对象
*
* @param id
* @return
*/
public Boy get(String id); /**
* 获得所有boy域对象
*
* @return
*/
public List<Boy> getAll(); /**
* 依据boy 属性条件查询boy列表
*
* @param phone
* 空或者null值将不作为查询条件
* @param sex
* 空或者null值将不作为查询条件
* @return
*/
public List<Boy> queryBoys(String phone, String sex); }

(6)BoysDAO 接口实现类:

开始测试:

package com.jmesa.test.dao.hibernate;

import java.sql.SQLException;
import java.util.List; import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.jmesa.test.dao.BoysDAO;
import com.jmesa.test.model.Boy; public class BoysDAOImpl extends HibernateDaoSupport implements BoysDAO { public Boy get(String id) {
return (Boy) this.getHibernateTemplate().load(Boy.class, id);
} public List<Boy> getAll() {
return queryBoys(null, null);
} public List<Boy> queryBoys(String phone, String sex) {
DetachedCriteria query = DetachedCriteria.forClass(Boy.class);
if (phone != null && !phone.equals("")) {
query.add(Property.forName("phone").eq(phone));
}
if (sex != null && !sex.equals("")) {
query.add(Property.forName("sex").eq(sex));
}
return this.getHibernateTemplate().findByCriteria(query);
} public void save(Boy boy) {
this.getHibernateTemplate().save(boy); } public void update(Boy boy) {
this.getHibernateTemplate().update(boy);
} }

基于AbstractTransactionalDataSourceSpringContextTests 创建测试基类:

package com.jmesa.test.integrateTest;

import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;

public class BaseDataSourceSpringContextIntegrationTest extends
AbstractTransactionalDataSourceSpringContextTests { //加载spring配置文件,其路径在classpath的根目录下
private static final String[] configFiles = new String[] {
"applicationContext-resources.xml", "applicationContext-dao.xml" }; //设置dao类的注入方式,默认为类型注入,此处改为名称注入 public BaseDataSourceSpringContextIntegrationTest() {
this.setAutowireMode(AUTOWIRE_BY_NAME);
} //通过此方法提供spring配置文件 protected String[] getConfigLocations() {
return configFiles;
}
}

BoysDAO的测试类:

package com.jmesa.test.integrateTest;

import java.util.List;

import org.junit.Assert;
import org.junit.Test; import com.jmesa.test.common.EntityFilters;
import com.jmesa.test.common.EntitySorts;
import com.jmesa.test.dao.BoysDAO;
import com.jmesa.test.model.Boy; /**
* @author jack
*/
public class BoyDAOTest extends BaseDataSourceSpringContextIntegrationTest {
private BoysDAO boysDAO; public BoyDAOTest(){
}
/**
* 必须要提供变量boysDAO的setter方法,这样注入才会成功
*/
public void setBoysDAO(BoysDAO boysDAO) {
this.boysDAO = boysDAO;
} @before public void initialize(){ } @after public void destroy(){ } @Test
public void testGetAll(){
int count = this.countRowsInTable("boys");
Assert.assertEquals(boysDAO.getAll().size(),count);
}
@Test
public void testQueryBoys(){
Assert.assertEquals(0,boysDAO.queryBoys("www", "wwww").size());
Assert.assertEquals(1,boysDAO.queryBoys("eee", "33").size());
}
@Test
public void testSave(){
int boysCount = this.countRowsInTable("boys");
String phone ="13401108995";
String sex = "1";
String address = "南京路";
Boy boy = new Boy();
boy.setPhone(phone);
boy.setSex(sex);
boy.setAddress(address);
boysDAO.save(boy);
Assert.assertEquals(boysCount+1, this.countRowsInTable("boys"));
}
@Test
public void testGetBoysCountWithFilter(){
EntityFilters entityFilters = new EntityFilters();
int count = boysDAO.getBoysCountWithFilter(entityFilters);
Assert.assertEquals(20, count);
EntityFilters entityFilters1 = new EntityFilters();
entityFilters1.addFilter("phone", "342432");
int size = entityFilters1.filterSize();
int count1 = boysDAO.getBoysCountWithFilter(entityFilters1);
Assert.assertEquals(1, count1);
}
@Test
public void testGetBoysWithFilterAndSort(){
EntityFilters entityFilters = new EntityFilters();
//entityFilters.addFilter("phone", "342432");
EntitySorts entitySorts = new EntitySorts();
entitySorts.addSort("phone", "desc");
List<Boy> boysList = boysDAO.getBoysWithFilterAndSort(entityFilters, entitySorts, 0, 10);
Assert.assertEquals(10, boysList.size());
Boy boy = boysList.get(0);
Assert.assertEquals("ww",boy.getPhone() ); }
}

此处测试用到了 AbstractTransactionalDataSourceSpringContextTests 的四方面的功能:

1. 加载spring的资源配置文件

2. dao bean 引入测试类

3. 简便的函数使用,如:countRowsInTable

4. 事务自动回滚.

请注意此BoyDAOTest测试类中使用@before,@after修饰的方法在测试中没有被执行, 可能原因是BoyDAOTest 间接继承了TestCase类,要想执行此类方法,必须沿用以前版本的junit的setUp,tearDown

方法,然而AbstractTransactionalDataSourceSpringContextTests 类已经overide此方法,并且加了final修饰,其子类不可以在overide了. 所以加入类似before,after这样的方法,目前还没有想出比较好的办法? 还请大侠们赐教.

使用 Spring 2.5 TestContext 测试DAO层的更多相关文章

  1. 使用 Spring 2.5 TestContext 测试框架

    Spring 2.5 TestContext 测试框架用于测试基于 Spring 的程序,TestContext 测试框架和低版本 Spring 测试框架没有任何关系,是一个全新的基于注解的测试框架, ...

  2. 我们应该测试 DAO 层吗?

    应该测试 DAO 层吗? 网上有很多人讨论单元测试是否应该包含 DAO 层的测试.笔者觉得,对于一些主要是crud的业务来说,service层和controller层都会非常薄,而主要的逻辑都落在ma ...

  3. 使用Unitils测试DAO层

    Spring 的测试框架为我们提供一个强大的测试环境,解决日常单元测试中遇到的大部分测试难题:如运行多个测试用例和测试方法时,Spring上下文只需创建一次:数据库现场不受破坏:方便手工指定Sprin ...

  4. spring boot 集成 mybatis 单元测试Dao层 控制台报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    最近帮同学做毕业程序,采用后端spring boot + mybatis + H2,将框架搭好进行各层的单元测试时,在dao层就出现了错,如图 于是在网上找各种资料,有的说是xml文件和接口没有一一对 ...

  5. Spring配置连接池和 Dao 层使用 jdbcTemplate

    1.Spring 配置 c3p0 连接池 (1)导入jar包(Maven项目) <dependency> <groupId>com.mchange</groupId> ...

  6. dbunit进行DAO层Excel单元测试

    DAO层测试难点 可重复性,每次运行单元测试,得到的数据是重复的 独立性,测试数据与实际数据相互独立 数据库中脏数据预处理 不能给数据库中数据带来变化 DAO层测试方法 使用内存数据库,如H2.优点: ...

  7. 基于dbunit进行mybatis DAO层Excel单元测试

    DAO层测试难点 可重复性,每次运行单元测试,得到的数据是重复的 独立性,测试数据与实际数据相互独立 数据库中脏数据预处理 不能给数据库中数据带来变化 DAO层测试方法 使用内存数据库,如H2.优点: ...

  8. Spring框架之使用JdbcTemplate开发Dao层程序

    简介: JdbcTemplate开发dao层程序     由Spring框架给我们提供,Spring提供的很多操作数据源(关系型数据库,二维表格模型,有明确的行和列(mysql/orcal等) 非关系 ...

  9. mybatis dao 层开发简易版 非整合 spring

    同样老习惯,先上项目结构截图 首先 补充上篇文中缺失的 mysql demo 用的 小脚本 drop database if exists mybatis; CREATE DATABASE `myba ...

随机推荐

  1. 关于SelectedItems的问题

    在做俄罗斯方块的时候写了以下一段代码: private void listView1_SelectedIndexChanged(object sender, EventArgs e)        { ...

  2. angularJS之站在jQuery的肩膀上

    jQuery:用更少的代码,实现更强悍的功能 托互联网日新月异发展的福,浏览器变成了人们接入互联网的入口,而JavaScript 这个曾经的小语种,终于成功地站到了舞台的中央,唤起了开发者的兴趣. 浏 ...

  3. MVC验证06-自定义错误信息

    原文:MVC验证06-自定义错误信息 本文体验自定义错误信息.   系统默认的错误信息 在"MVC验证02-自定义验证规则.邮件验证"中,我们自定义了一个验证Email的类.如果输 ...

  4. POJ 3654 &amp; ZOJ 2936 &amp; HDU 2723 Electronic Document Security(模拟)

    题目链接: PKU:http://poj.org/problem?id=3654 ZJU:http://acm.zju.edu.cn/onlinejudge/showProblem.do?proble ...

  5. 让IE6支持position:fixed的方法,CSS expression与JavaScript eval讲解

    做吸顶效果或是固定效果时,使用position:fixed无非是最方便的,可是万恶的IE6是没有fixed这个属性值的,而我们要使IE6能够像fixed一样固定在浏览器中的某个位置,使用onscrol ...

  6. Windows 8.1 store app 开发笔记

    原文:Windows 8.1 store app 开发笔记 零.简介 一切都要从博彦之星比赛说起.今年比赛的主题是使用Bing API(主要提到的有Bing Map API.Bing Translat ...

  7. leetcode第24题--Reverse Nodes in k-Group

    problem: Given a linked list, reverse the nodes of a linked list k at a time and return its modified ...

  8. PHP专业开发IDE——Zend Studio 10.5预览版发布

    Zend Studio是新一代的PHP IDE,高效的开发和维护PHP代码是它的核心.Zend公司目前已发布了Zend Studio 10.5预览版,预览版中提高了快速响应能力和时时误差检查.因此使用 ...

  9. 输入 URL 到页面完成加载过程中的所有发生的事情?

    转到浏览器中输入URL给你一个页面后,.有些事情,你每天都在使用,学的是计算机网络知道是怎么回事.DNS解析然后页面的回馈,只是要讲好还是有难度. 之前fex团队的nwind专门写过这个问题的博客: ...

  10. python网络爬虫进入(一)——简单的博客爬行动物

    最近.对于图形微信公众号.互联网收集和阅读一些疯狂的-depth新闻和有趣,发人深思文本注释,并选择最佳的发表论文数篇了.但看着它的感觉是一个麻烦的一人死亡.寻找一个简单的解决方案的方法,看看你是否可 ...