SpringMVC的Web程序可以使用Spring mock进行测试,不用每一次都需要部署到容器里边,mock会帮你模拟Web环境。
部署SpringMVC的Web程序,我们需要在web.xml里面设置listener来创建我们的ApplicationContext,在mock里面,我们也需要创建ApplicationContext。
测试类需要继承AbstractDependencyInjectionSpringContextTests,并覆盖protected String[] getConfigLocations()方法,这个方法就是告诉mock你的applicationContext配置文件和-servlet.xml文件在哪个地方。例子:
@Override
protected String[] getConfigLocations() {
return new String[]{"applicationContext-*.xml","file:D:\\MyApp\\test\\web\\WEB-INF\\dispatcher-servlet.xml"};
}
这里注意,默认是在类路径里面找。我的applicationContext配置文件放在了类路径,所以不需要加其他的路径,否则,使用物理路径。
之后我做一个简单的测试。我现在有一个LoginController.java,用来判断登陆的userid和userpwd是否正确,正确则去到success.jsp,否则去到fail.jsp。假设现在有一个账号aa,密码是bb。
我要先在ApplicationContext里面拿控制器的实例出来:
LoginController loginController = (LoginController) this.applicationContext.getBean("loginController");
这个applicationContext通过覆盖的方法getConfigLocations创建的。
然后我们使用MockHttpServletRequest类和MockHttpServletResponse类模拟HttpServletRequest和HttpServletResponse:
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
再设置request的参数:
request.setMethod("POST");
request.addParameter("userid","aa");
request.addParameter("userpwd","bb");
最后调用loginController的login方法(我这里使用MutiActionController):
ModelAndView mav = loginController.login(request,response);
完整的测试代码如下:
public class TestLoginController extends AbstractDependencyInjectionSpringContextTests {
@Override
protected String[] getConfigLocations() {
return new String[]{"applicationContext-*.xml","file:D:\\MyApp\\test\\web\\WEB-INF\\dispatcher-servlet.xml"};
}
@SuppressWarnings("static-access")
public void testLogin() throws MalformedURLException, IOException{
LoginController loginController = (LoginController) this.applicationContext.getBean ("loginController");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setMethod("POST");
request.addParameter("userid","aa");
request.addParameter("userpwd","bb");
ModelAndView mav = loginController.login(request,response);
assertEquals("success",mav.getViewName());
}
}