利用Spring的mock对控制层进行单元测试
作者:网络转载 发布时间:[ 2013/8/22 13:26:57 ] 推荐标签:
spring的配置文件此处省略
单元测试:
public class CaseControllerTest {
private static final Log logger = LogFactory.getLog(CaseControllerTest.class);
private CaseController controller = null;
private XmlWebApplicationContext ctx;
@Before
public void setUp() throws Exception {
String[] paths = {"spring-servlet-test.xml" };
ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(paths);
ctx.setServletContext(new MockServletContext(""));
ctx.refresh();
controller = (CaseController) ctx.getBean("caseController");
}
@After
public void tearDown() throws Exception {
ctx.close();
}
@Test
public void testListJson() {
logger.info("*****testListJson start**********");
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
request.setRequestURI("/case/listJson");
request.addParameter("name", "name");
List<String> result = controller.listJson(request, response);
logger.info("*****result:" + result);
Assert.assertTrue("result is empty", !result.isEmpty());
logger.info("*****testListJson end**********");
}
@Test
public void testList() {
logger.info("*****testList start**********");
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
request.setRequestURI("/case/list");
request.addParameter("name", "name");
String returnStr = controller.list(request, response);
List<String> result = (List<String>) request.getAttribute("result");
logger.info("*****result:" + result);
logger.info("*****returnStr:" + returnStr);
logger.info("*****testList end**********");
}
}
注意点:
1.spring-servlet-test.xml配置文件要对;
2.controller的bean首字母是小写即caseController;
3.可以通过request response直接获取相应的数据,如request.getAttribute("result");
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11