How to unit test a Spring MVC controller using @PathVariable?

Posted by Martiner on Stack Overflow See other posts from Stack Overflow or by Martiner
Published on 2009-09-09T18:02:01Z Indexed on 2010/04/08 4:03 UTC
Read the original article Hit count: 645

Filed under:
|
|

I have a simple annotated controller similar to this one:

@Controller
public class MyController {
  @RequestMapping("/{id}.html")
  public String doSomething(@PathVariable String id, Model model) {
    // do something
    return "view";
  }
}

and I want to test it with an unit test like this:

public class MyControllerTest {
  @Test
  public void test() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/test.html");
    new AnnotationMethodHandlerAdapter()
      .handle(request, new MockHttpServletResponse(), new MyController());
    // assert something
  }
}

The problem is that AnnotationMethodHandlerAdapter.handler() method throws an exception:

java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.resolvePathVariable(AnnotationMethodHandlerAdapter.java:642)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolvePathVariable(HandlerMethodInvoker.java:514)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:262)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:146)

© Stack Overflow or respective owner

Related posts about spring-mvc

Related posts about java