在 spring (3.0) 的早期版本中,可以使用 ApplicationContext 中的 RequestMappingHandlerAdapter 和 HandlerMapping 对象通过正确的 url 测试您的控制器。但是,在 Spring 3.1 中,情况发生了变化,我用来完成这项工作的代码不再起作用。
如何在 Spring 3.1 中测试 Spring 控制器 url?例如,我想编写如下所示的代码:
ModelAndView modelAndView = handle("GET", "/businesses");
这样,除了控制器的动作逻辑之外,我还在测试我的映射。
特别是,我最感兴趣的是确保我可以传递会话属性并将它们正确传递给我的控制器操作的 @Valid 注释。
Spring 3.1有什么方法可以做到这一点吗?
这是我使用的代码:
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final HandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
final HandlerExecutionChain handler = handlerMapping.getHandler(request);
assertNotNull("No handler found for request, check you request mapping", handler);
final Object controller = handler.getHandler();
final HandlerInterceptor[] interceptors = handlerMapping.getHandler(request).getInterceptors();
for (HandlerInterceptor interceptor : interceptors) {
final boolean carryOn = interceptor.preHandle(request, response, controller);
if (!carryOn) {
return null;
}
}
return handlerAdapter.handle(request, response, controller);
}
protected ModelAndView handle(String method, String path, String queryString) throws Exception {
request.setMethod(method);
request.setRequestURI(path);
if(queryString != null) {
String[] parameters = queryString.split("&");
for(String parameter : parameters) {
String[] pair = parameter.split("=");
if(pair.length == 2) {
request.setParameter(pair[0], pair[1]);
} else {
request.setParameter(pair[0], "");
}
}
}
return handle(request, response);
}
protected ModelAndView handle(String method, String path, String attribute, Object object) throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(attribute, object);
request.setSession(session);
return handle(method, path, null);
}
protected ModelAndView handle(String method, String path) throws Exception {
return handle(method, path, null);
}
protected void assertContentType(ModelAndView modelAndView, String contentType) {
assertEquals(contentType, modelAndView.getView().getContentType());
}