title: How to unit test a Spring MVC controller using @PathVariable?
body: <p>I have a simple annotated controller similar to this one:</p>
  
  <pre><code>@Controller
  public class MyController {
    @RequestMapping("/{id}.html")
    public String doSomething(@PathVariable String id, Model model) {
      // do something
      return "view";
    }
  }
  </code></pre>
  
  <p>and I want to test it with an unit test like this:</p>
  
  <pre><code>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
    }
  }
  </code></pre>
  
  <p>The problem is that AnnotationMethodHandlerAdapter.handler() method throws an exception:</p>
  
  <pre><code>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)
  </code></pre>