web工程中spring+ibatis的单元测试-转
为了保证代码的正确,软件的质量,单元测试几乎是每个程序员都要面临的工作了;而开发中大部分的工作都涉及数据库的操作,也就是平时经常可以看到的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实现类代码是否正确了