为了保证代码的正确,软件的质量,单元测试几乎是每个程序员都要面临的工作了;而开发中大部分的工作都涉及数据库的操作,也就是平时经常可以看到的DAO了;由于是对数据库的操作,就必然有事务的问题了;如果是启动应用服务器,然后再模拟一个请求来验证Dao中的代码写得是否正确的话,那么面临的问题 首先就是 速度的问题也就是效率的问题,如果你的应用很大的话那么但就tomcat的启动就花费了一分钟左右的时间,如果用的服务器是weblogic的话就更加不用说了 其实就是问题的主次问题,我们现在要做的正事是测试Dao 但是如果放到服务器里面测试的话 可能有些问题就不是dao的问题了,但是我们必须解决,这样做 显然很多时候就有点本末倒置了 ;因此我采用的方法是利用spring+ibatis+junit在本地测试的方法 大体步骤如下

一  建立一个测试的基类 AbstractTestCase 代码如下

package com.skywin.workorder.dao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public abstract class AbstractTestCase extends TestCase {
    protected ApplicationContext ctx = null;

public AbstractTestCase() {
        // 测试工作流
        //ctx = new ClassPathXmlApplicationContext("testApplicationContext.xml");
        // 测试DAO
          ctx =new ClassPathXmlApplicationContext(
         "_applicationContext-iBatis.xml"); 
    }
}

二 第一步中文件 _applicationContext-iBatis.xml 的路径为 工程名字\conf\_applicationContext-iBatis.xml ,是spring的配置文件进行事务属性等相关配置  代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<!--
    <import  resource="classpath:_applicationContext-authrization.xml"/>
-->

<import  resource="classpath:workorder-module.xml"/>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                 <value>jdbc-template.properties</value> 
            </list>
        </property>
    </bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean> 
<!--
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@10.244.112.130:41521:gmcctest"/>
        <property name="username" value="gmcc"/>
        <property name="password" value="gmcc"/>
        <property name="initialSize" value="1"/>
        <property name="maxActive" value="15"/>
    </bean>
-->

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="configLocation" value="sqlmap-config-template.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

<bean id="baseTxService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" 
        abstract="true"> 
        <property name="transactionManager" ref="transactionManager"/> 
        <property name="proxyTargetClass" value="true"/> 
        <property name="transactionAttributes"> 
            <props> 
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> 
                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> 
                <prop key="save*">PROPAGATION_REQUIRED</prop> 
                <prop key="remove*">PROPAGATION_REQUIRED</prop> 
                <prop key="update*">PROPAGATION_REQUIRED</prop>
                <!--  instead of  select .. for update
                <prop key="global*">
                    PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE
                </prop>
                -->
            </props> 
        </property> 
    </bean>

</beans>

三 第二步中涉及DataSource,其配置信息包含在 jdbc-template.properties 文件中 文件路径为

工程目录\conf\jdbc-template.properties 代码如下

# Properties file with JDBC-related settings.
# Applied by PropertyPlaceholderConfigurer from "applicationContext.xml".
# Targeted at system administrators, to avoid touching the context XML files.

#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/mps
#jdbc.username=root
#jdbc.password=skywin

jdbc.initialSize=1
jdbc.maxActive=10

jdbc.driverClassName=oracle.jdbc.OracleDriver 
#jdbc.url=jdbc:oracle:thin:@10.244.112.130:41521:gmcctes
#jdbc.url=jdbc:oracle:thin:@10.244.112.130:1521:gmccmpp
jdbc.url=jdbc:oracle:thin:@192.168.100.235:1521:mpptest
jdbc.username=gmcc
jdbc.password=skywin 
#imageDatabase.lobHandler=oracleLobHandler

三 第二步中的   <property name="configLocation" value="sqlmap-config-template.xml"/> 为ibatis的中枢文件 文件路径是   工程目录\conf\sqlmap-config-template.xml 代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<!-- Leonel Wong 2008-11-6 17:24:04 -->
<sqlMapConfig>
    <sqlMap resource="ibatis-conf/MpsAppendixInf.xml" />
    <sqlMap resource="ibatis-conf/MpsDispatchLog.xml" />
    <sqlMap resource="ibatis-conf/MpsFunctionType.xml" />
    <sqlMap resource="ibatis-conf/MpsFundType.xml" />
    <sqlMap resource="ibatis-conf/MpsInGatewayInf.xml" />
    <sqlMap resource="ibatis-conf/MpsModuleInf.xml" />
    <sqlMap resource="ibatis-conf/MpsOperationType.xml" />
    <sqlMap resource="ibatis-conf/MpsOrderClaimant.xml" />
    <sqlMap resource="ibatis-conf/MpsPayType.xml" />
    <sqlMap resource="ibatis-conf/MpsProcessApproveLog.xml" />
    <sqlMap resource="ibatis-conf/MpsProcessLog.xml" />
    <sqlMap resource="ibatis-conf/MpsProcessRemark.xml" />
    <sqlMap resource="ibatis-conf/MpsReceiveOrderLog.xml" />
    <sqlMap resource="ibatis-conf/MpsServiceInfo.xml" />
    <sqlMap resource="ibatis-conf/MpsUploadFile.xml" />
    <sqlMap resource="ibatis-conf/MpsUrgentLevel.xml" />
    <sqlMap resource="ibatis-conf/MpsVerifyLog.xml" />
    <sqlMap resource="ibatis-conf/MpsWorkOrder.xml" />
    <sqlMap resource="ibatis-conf/MpsWorkOrderCancelLog.xml" />
    <sqlMap resource="ibatis-conf/MpsWorkOrderCloseLog.xml" />
    <sqlMap resource="ibatis-conf/MpsWorkOrderType.xml" />
    <sqlMap resource="ibatis-conf/MpsOperatorInf.xml" />
    <sqlMap resource="ibatis-conf/MpsOrderServiceInfo.xml" />
    <sqlMap resource="ibatis-conf/MpsTree.xml" />
    <sqlMap resource="ibatis-conf/MpsOperatorTree.xml" />
    <sqlMap resource="ibatis-conf/MpsTest.xml" /> 
    <sqlMap resource="ibatis-conf/MpsSpInfo.xml" />
</sqlMapConfig>

四 ormpping文件,这里以MpsTest.xml文件为例子,该文件路径是

工程目录/conf\ibatis-conf\MpsTest.xml 代码如下:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<!-- qjk 2009-02-02 -->
<sqlMap namespace="MpsTest">

<resultMap id="result" class="com.skywin.workorder.model.MpsTest">
        <result property="testId" column="testid" columnIndex="1" />
        <result property="mpsWorkOrder.orderId" column="orderid" columnIndex="2" />
        <result property="wfid" column="wfid" columnIndex="3" />
        <result property="testResult" column="testResult" columnIndex="4" />
        <result property="testDate" column="testdate" columnIndex="5" />
        <result property="testPerson" column="testPerson" columnIndex="6" />
        <result property="testDesc" column="testDesc" columnIndex="7" />
    </resultMap>
    
    <insert id="saveMpsTest">
         insert into wo_test(testid,orderid,wfid,testResult,testdate,testPerson,testDesc)
         values(#testId#,#mpsWorkOrder.orderId#,#wfid#,#testResult#,#testDate#,#testPerson#,#testDesc#)
    </insert> 
    
    <delete id="deleteMpsTestById">
       delete from wo_test where testid=#value#
    </delete>
    
    <select id="findAllMpsTest" resultMap="result">
        select * from wo_test
    </select>
    
    <select id="findAllMpsTestCount" resultClass="Long">
       select count(*) from wo_test
    </select>
    
    <select id="findMpsTestNextSeq" resultClass="Long">
         select wo_test_seq.nextval from dual
    </select>
    
    
    
    
</sqlMap>

五 dao实现类代码:

package com.skywin.workorder.dao.Impl;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.skywin.workorder.dao.MpsTestDao;
import com.skywin.workorder.model.MpsTest;
import com.skywin.workorder.util.ListResult;

public class MpsTestDaoImpl extends SqlMapClientDaoSupport implements MpsTestDao {

public int deleteMpsTestById(Long testId) {
        return getSqlMapClientTemplate().delete("deleteMpsTestById", testId);
    }

public List findAllMpsTest(int pagesize, int pageIndex) {
        return getSqlMapClientTemplate().queryForList("findAllMpsTest", null, pageIndex*pagesize, pagesize);
    }

public Long findAllMpsTestCount() {
        return (Long) getSqlMapClientTemplate().queryForObject("findAllMpsTestCount", null);
    }

public ListResult pageAllMpsTest(int pagesize, int pageIndex) {
        ListResult listResult=new ListResult();
        listResult.setResult(findAllMpsTest(pagesize,pageIndex));
        listResult.setCount(findAllMpsTestCount());
        return listResult;
    }

public MpsTest saveMpsTest(MpsTest mpsTest) {
        getSqlMapClientTemplate().insert("saveMpsTest",mpsTest);
        return mpsTest;
    }

public Long findMpsTestNextSeq() {
        return (Long) getSqlMapClientTemplate().queryForObject("findMpsTestNextSeq", null);
    }

}

六 实体bean代码(MpsTest)

package com.skywin.workorder.model;

import java.io.Serializable;
import java.util.Date;

/**测试记录*/
public class MpsTest implements Serializable{
    
    /**主键*/
    private Long testId;
    
    /**关联工单*/
    private MpsWorkOrder mpsWorkOrder;
    
    /**工作流id*/
    private Long wfid;
    
    /**测试人*/
    private String testPerson;
    
    /**测试是否通过*/
    private int testResult;
    
    /**测试结果描述*/
    private String testDesc;
    
    /**测试日期*/
    private Date testDate;

public MpsWorkOrder getMpsWorkOrder() {
        return mpsWorkOrder;
    }

public void setMpsWorkOrder(MpsWorkOrder mpsWorkOrder) {
        this.mpsWorkOrder = mpsWorkOrder;
    }

public String getTestDesc() {
        return testDesc;
    }

public void setTestDesc(String testDesc) {
        this.testDesc = testDesc;
    }

public String getTestPerson() {
        return testPerson;
    }

public void setTestPerson(String testPerson) {
        this.testPerson = testPerson;
    }

public int getTestResult() {
        return testResult;
    }

public void setTestResult(int testResult) {
        this.testResult = testResult;
    }

public Date getTestDate() {
        return testDate;
    }

public void setTestDate(Date testDate) {
        this.testDate = testDate;
    }

public Long getTestId() {
        return testId;
    }

public void setTestId(Long testId) {
        this.testId = testId;
    }

public Long getWfid() {
        return wfid;
    }

public void setWfid(Long wfid) {
        this.wfid = wfid;
    }

}

七 建立一个jUnit测试类 测试第六步中dao的方法 其实改类本质上也是一个java类 要想成功的测试某个方法则方法名字不以test开头 代码如下 :

package com.skywin.workorder.dao;

import java.util.Date;
import java.util.List;

import com.skywin.workorder.model.MpsTest;
import com.skywin.workorder.model.MpsWorkOrder;
import com.skywin.workorder.util.ListResult;

public class MpsTestDaoTest extends AbstractTestCase {
    MpsTestDao dao;
    public MpsTestDaoTest(){
        super();
        dao=(MpsTestDao) ctx.getBean("woTestDao");
        System.out.println("dao"+dao);
        
    }
    
     public void  testsaveMpsTest(){ 
        System.out.println("go go go");
         MpsTest t=new MpsTest(); 
    
        t.setTestId(new Long(-105));
        t.setWfid(new Long(-15));
        System.out.println("2222222");
    MpsWorkOrder mpsWorkOrder=new MpsWorkOrder();
        mpsWorkOrder.setOrderId(new Long(-20));
        t.setMpsWorkOrder(mpsWorkOrder);
        
        t.setTestResult(-50);
        t.setTestPerson("kkkkk");
        t.setTestDesc("hao hao");
        t.setTestDate(new Date());
        dao.saveMpsTest(t); 
    }
    
    public void _testfindAllMpsTestCount(){
        Long c=dao.findAllMpsTestCount();
        System.out.println("c---"+c);
    }
    
    public void _testfindAllMpsTest(){
        List  list=dao.findAllMpsTest(3, 1);
        for(int i=0;i<list.size();i++){
            MpsTest t=(MpsTest) list.get(i);
            System.out.println(t.getTestId());
        }
        System.out.println(list);
    }
    
    
    public void _testpageAllMpsTest(){
        ListResult l=dao.pageAllMpsTest(3, 1);
        System.out.println(l.getCount());
    }
    
    public void _testfindMpsTestNextSeq(){
        Long s=dao.findMpsTestNextSeq();
       System.out.println("s---"+s);
    }
    
    
    
    public void test(){
        dao.deleteMpsTestById(new Long(-100));
    }
}

完成以上步骤后 运行JUnit就可以了,结果是红条还是绿条就看你dao实现类代码是否正确了。

原文地址:http://kai2008.iteye.com/blog/324145

web工程中spring+ibatis的单元测试--转载的更多相关文章

  1. 如何在Web工程中实现任务计划调度

    转载自: http://www.oschina.net/question/146385_37793?sort=time 下面就Servlet侦听器结合Java定时器来讲述整个实现过程.要运用Servl ...

  2. web工程中URL地址的推荐写法

    三.web工程中URL地址的推荐写法 使用c标签<c:url value="" /> 会自动添加项目名 -> value中的值 前面要加 “/” 在JavaWeb ...

  3. web工程中URL地址的写法

    在开发中我们不可避免的要碰到许多需要写URL地址的情况,这常常让我们感到头疼.下面笔者推荐一种简单的做法.URL地址分为绝对路径和相对路径两种.相对路径又分为相对资源路径和相对根路径.显然绝对路径在开 ...

  4. Web环境中Spring的启动过程

    1.spring不但可以在JavaSE环境中应用,在Web环境中也可以广泛应用,Spring在web环境中应用时,需要在应用的web.xml文件中添加如下的配置: …… <context-par ...

  5. web工程中的各种路径(eclipse开发)

    目前遇到的 web 工程中要写url和路径的文件有 webContent中.jsp/.html :action src中的servlet类 : 映射地址.重定向.请求转发.访问资源文件(webCont ...

  6. 读取web工程中.properties资源文件的模板代码

    读取web工程中.properties资源文件的模板代码 // 读取web工程中.properties资源文件的模板代码 private void test2() throws IOException ...

  7. 多工程:基于Maven的SSM(Spring,SpringMvc,Mybatis)整合的web工程(中)

    上篇用了单工程创建了SSM整合的web工程(http://www.cnblogs.com/yuanjava/p/6748956.html),这次我们把上篇的单工程改造成为多模块工程 一:创建对应的多工 ...

  8. 关于eclipse中MAVEN WEB工程中编译问题

    这几天是被java的环境搞疯了,我先是搭了一个spring+springmvc+mybatis的工程,在家里跑了一下,没有问题,把工程带到公司里用,却一直不能使用. 按常理来说,只要工程发生一点变化, ...

  9. web工程中web.xml元素加载顺序以及配置实例

    简介 web.xml是web工程的配置文件,容器加载web工程时,会首先从WEB-INF中查询web.xml,并加载其中的配置信息,可以将web.xml认为是web工程的入口. web.xml中包含有 ...

随机推荐

  1. 从 C++ 到 Qt(命令行编译)good

    从 C++ 到 Qt 转载自:http://hi.baidu.com/cyclone/blog/item/8f8f08fa52d22f8758ee9006.html Qt 是 C++ 的库,Qt在an ...

  2. new[]上面居然有一个内存计数,怪不得delete[]从来不出错

    开眼界了,留个爪,以后再仔细看几遍: http://www.cnblogs.com/hazir/p/new_and_delete.html

  3. Android List去掉重复数据

    今天用数据库获取数据发现有个字段的数据重复了,于是就写了下面这个方法去除重复的数据. public static List<String> removeDuplicate(List< ...

  4. Rails3.2.3+ruby1.9.3 环境搭建,提示安全警告

    错误描述: 照着教程搭建了Rails的环境,能够正常运行,但是会但一个警告,如下: SECURITY WARNING: No secret option provided to Rack::Sessi ...

  5. 【HDOJ】1230 火星A+B

    个人觉得这道题没那么水,wa了几次,才发现自己居然没有给srcb数组reset,打错了.搞死啊. #include <stdio.h> #include <string.h> ...

  6. 使用vs2010进行驱动开发的补充

    看到前面的一篇文章 ,在这里http://www.cnblogs.com/wubiyu/archive/2010/05/17/1737420.html vs2010配置驱动开发基本上按照如上所说就差不 ...

  7. jQuery-单击文字或图片内容放大显示效果插件

    css很强大,jQuery也很强大,两者结合在一起就是无比强大.这里要介绍的这个单击文字或图片内容放大居中显示的效果就是这两者结合的产物. 先来介绍css和jQuery各自发挥了什么作用吧: css: ...

  8. WCF大数据量传输解决方案

    文章内容列表:1. 场景:2. 解决方案3. WCF契约与服务实现设计静态图4. WCF契约与服务实现设计详细说明6. 服务端启动服务代码:7. 客户端代码8.   WCF大数据量传输解决方案源码下载 ...

  9. DNS----域名解析系统

    DNS就是域名解析系统,它可以将IP转换成域名,也可以将域名转换成IP 1. 安装DNS服务       开始—〉设置—〉控制面板—〉添加/删除程序—〉添加/删除Windows组件—〉“网络服务”—〉 ...

  10. 两种应该掌握的排序方法--------1.shell Sort

    先了解下什么都有什么排序算法 https://en.wikipedia.org/wiki/Sorting_algorithm http://zh.wikipedia.org/zh/%E6%8E%92% ...