idea中Spring项目的IUnit4单元测试
一、在想单元测试的方法类中,快捷键 Ctrl + Shift + T ,选择Create new test…,选择想要测试的方法。此快捷键会在本类的同一个文件夹下创建一个测试类。(如何创建并指定了测试文件夹,会在test文件夹下同目录下创建测试类)
二、添加@RunWith和@ContextConfiguration注解
package com.caxs.mdd.cfs.webservice;
import com.alibaba.dubbo.common.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.caxs.mdd.base.domain.BaseConstant;
import com.caxs.mdd.constant.Constant;
import com.caxs.mdd.loan.appl.service.IApplService;
import com.caxs.mdd.loan.appl.service.IApplStateService;
import com.caxs.mdd.webservice.service.cmistomdd.*;
import org.apache.commons.collections.map.HashedMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml",
"classpath:dubboContext.xml",
"classpath:dubboContext-reference.xml",
"classpath:applicationContext-webservice.xml"})
public class CFSRequestControllerTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
public IApplService applService;
@Autowired
@Qualifier("applStateService")
public IApplStateService applStateService;
@Autowired
public IWd0126Service wd0126Service;
@Test
public void cfChangeInterface() {
String json = "{\n" +
"\t\"reqDataMsgInfo\": {\n" +
"\t\t\"reqJson\": {\n" +
"\t\t\t\"reqVehModeData\": {\n" +
"\t\t\t\t\"classSeq\": 303851249,\n" +
"\t\t\t\t\"manufSeq\": 300000444,\n" +
"\t\t\t\t\"manufCde\": \"U113431\",\n" +
"\t\"reqHeadData\": {\n" +
"\t\t\"bchCde\": \"900000000\",\n" +
"\t\t\"msgId\": \"0001389547\",\n" +
"\t\t\"msgNo\": \"0125\",\n" +
"\t\t\"msgRef\": \"0001389548\",\n" +
"\t\t\"reqCode\": \"CFS\",\n" +
"\t\t\"teller\": \"lixiaole\",\n" +
"\t\t\"workData\": \"20181128\",\n" +
"\t\t\"workTime\": \"135539\"\n" +
"\t}\n" +
"}";
Map frontData = JSON.parseObject(json);
logger.info("接收报文:\n" + JSON.parseObject(json));
Object reqDataMsgInfo = frontData.get("reqDataMsgInfo");
Object reqHeadData = frontData.get("reqHeadData");
Map map = (Map) reqHeadData;
String msgNo = map.get("msgNo").toString();
logger.info("cfs" + msgNo + "接口接收报文:\n" + frontData);
Map resultMap = new HashedMap();
if (BaseConstant.msgNo_0126.equals(msgNo)) {
resultMap = wd0126Service.cfsDeal(reqDataMsgInfo);
}
if (Constant.SUCCESS_CODE.equals(resultMap.get("ecode"))) {
logger.info("success");
} else {
logger.info("error");
}
}
}
三、如果有启动参数,配置启动参数。(独立配置,如果你启动web或者service的时候已经配置过了启动参数,但是单元测试类启动的时候还是需要配置的)
四、运行测试类,单元测试