Announcement Announcement Module
Collapse
No announcement yet.
Problem with @PathVariable when using MockHttpServletRequest Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with @PathVariable when using MockHttpServletRequest

    Hi,

    I am trying to test my controller by using MockHttpServletRequest.

    This is the controller method I want to test (tested with 'curl http://localhost:8080/admin/admin/groups/0?format=xml', I get my group marshalled to xml, so it works):


    @RequestMapping(value = "/groups/{groupId}", method = RequestMethod.GET)
    public Group getGroup(@PathVariable Long groupId,
    HttpServletResponse response) {
    Group group = adminService.getGroup(groupId);
    if (group == null) {
    response.setStatus(HttpServletResponse.SC_NOT_FOUN D);
    return null;
    }
    return group;
    }


    Here is the JUnit test method I use:


    @Test
    public void testGetGroupValidId() throws Exception {
    final Group group = new Group();
    final String name = "new group name";
    group.setName(name);
    final String description = "new group description";
    group.setDescription(description);
    final Long id = 0L;
    group.setId(id);
    mockContext.checking(new Expectations() {
    {
    oneOf(adminService).getGroup(id);
    will(returnValue(group));
    }
    });

    request.setMethod(RequestMethod.GET.toString());
    request.setRequestURI("/groups/0");
    HashMap<String, String> pathVariablesMap = new HashMap<String, String>();
    pathVariablesMap.put("groupId", "0");
    request.setAttribute(HandlerMapping.URI_TEMPLATE_V ARIABLES_ATTRIBUTE,
    pathVariablesMap);

    ModelAndView modelAndView = handlerAdapter.handle(request, response,
    adminController);
    ModelAndViewAssert.assertAndReturnModelAttributeOf Type(modelAndView,
    "group", Group.class);

    mockContext.assertIsSatisfied();
    }


    My problem is that when I do not call request.setAttribute(HandlerMapping.URI_TEMPLATE_V ARIABLES_ATTRIBUTE, pathVariablesMap); I get an exception:
    java.lang.IllegalStateException: Could not find @PathVariable [groupId] in @RequestMapping

    I did not find much documentation (the Spring 3 reference and javadoc were not very helpful ) or example of tests done with MockHttpServletRequest and @PathVariable, and had to debug into org.springframework.web.servlet.mvc.annotation.Ann otationMethodHandlerAdapter ServletHandlerMethodInvoker resolvePathVariable method to find this.

    So my question: is this the way it is supposed to work??

    Thanks,
    Claire
Working...
X