EasyMock模拟HttpServletRequest进行JUnit测试

使用JUnit测试的时候,HttpServletRequest需要进行模拟才可以,所以就用到了EasyMock,使用方法如下:

public static void main(String[] args) throws UnsupportedEncodingException {
	String queryString = "name=acgist&age=24";
	String[] queryStrings = queryString.split("&");
	int index;
	String key, value;
	Map<String, String> map = new HashMap<String, String>();
	HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
	for (String paras : queryStrings) {
		index = paras.indexOf("=");
		key = paras.substring(0, index);
		value = URLDecoder.decode(paras.substring(index + 1), "utf-8");
		map.put(key, value);
		EasyMock.expect(request.getParameter(key)).andReturn(value).times(1); // 只能使用一次
	}
	EasyMock.expect(request.getParameterMap()).andReturn(map).anyTimes(); // 没有次数限制
	EasyMock.replay(request);
	System.out.println(request.getParameter("age"));
//		System.out.println(request.getParameter("age")); // 两次保存
	System.out.println(request.getParameter("name"));
	System.out.println(request.getParameterMap()); // 无次数限制
	System.out.println(request.getParameterMap());
}

参考文章:https://www.ibm.com/developerworks/cn/opensource/os-cn-easymock/