利用Spring的mock对控制层进行单元测试

大环境概述:

java -version
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
Java HotSpot(TM) Client VM (build 17.0-b16, mixed mode, sharing)

spring的版本:3.1.0.RELEASE

spring-mock的版本:1.2.6

采用Spring 注解mvc

控制层:

@Controller
@RequestMapping("/case")
public class CaseController {
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public String list(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		request.setAttribute("name", name);
		List<String> result = new ArrayList<String>();
		result.add("result1");
		result.add("result2");
		result.add("result3");
		request.setAttribute("result", result);
		return "case/list";
	}

	@RequestMapping(value = "/listJson", method = RequestMethod.POST)
	@ResponseBody
	public List<String> listJson(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		List<String> result = new ArrayList<String>();
		result.add("result1");
		result.add("result2");
		result.add("result3");
		return result;
	}

}

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");

 

你可能感兴趣的:(spring)