junit作为最常用的测试框架,而spring是最佳的整合框架,开发j2ee的程序测试,需要先加载web的上下文环境才能完成业务类的测试。
下面例子是搭建基于spring的框架环境
1.书写加载上下文环境的基础类
2.书写业务测试类
package com.taobao.mmp.service.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.taobao.hsf.hsfunit.HSFEasyStarter;
//import com.taobao.hsf.hsfunit.HSFEasyStarter;
/**
* 单元测试基类-测试的spring环境
* @author luohu
* @version 1.0
*
*/
public abstract class BaseTestCase {
/**
* Spring容器
*/
protected static ApplicationContext springContext = null;
static{
HSFEasyStarter.startFromPath("D:/java_tools/jboss-4.2.2.GA-ls/server/default/deploy/taobao-hsf.sar");
//HSFEasyStarter.startFromPath("d:/hsf/release");
}
/**
* 默认配置文件
*/
public static String[] paths = {
"persistence.xml",
"biz-manager.xml",
"biz-dao.xml",
"tdbm-config.xml",
"sql-map.xml",
"spring-hsf-consumer.xml",
//"client.xml",
//"spring-hsf-provider.xml.vm",
//"spring-hsf-mapping.xml.vm",
"biz-service.xml"
};
// "spring-hsf-consumer.xml"
/**
* 以默认的配置文件启动Spring容器
* @throws Exception
*/
public static void initSpringContext() throws Exception {
springContext = new ClassPathXmlApplicationContext(paths);
}
/**
* 以指定的配置文件启动Spring容器
* @throws Exception
*/
protected static void initSpringContext(String[] paths) throws Exception {
springContext = new ClassPathXmlApplicationContext(paths);
}
/**
* 销毁Spring容器
* @throws Exception
*/
protected static void destroySpringContext() throws Exception {
springContext = null;
}
}
/**
*测试类的书写,首先得加载配置环境
* @author luohu*/
public class MmpReadServiceTest extends BaseTestCase {
protected MmpReadService mmpReadService;
@Before
public void init() throws Exception {
if (null == mmpReadService) {
initSpringContext();
mmpReadService = (MmpReadService) springContext.getBean("mmpReadService");
}
}
@Test
public void testQuerySubUserInfoBySubId_根据子账号id获取子账号手机号(){
Long subId=2049919597L;
ResultBaseDO<SubUserInfoDO> result = mmpReadService.querySubUserInfoBySubUserId(subId);
if(result.isSuccess()&&result.getModule()!=null){
System.out.println("子账号ID"+result.getModule().getSubUserId()+"__子账号手机"+result.getModule().getMobilePhone());
}else{
System.out.println("查询在手机对象不存在");
}
}
}