Spring的MockMvc选择了错误的处理程序方法

时间:2018-04-09 11:25:22

标签: spring spring-boot spring-test spring-test-mvc

我有一个包含2种以上方法的控制器:

@RequestMapping(method = RequestMethod.GET, value = "/{uuid}", produces = "application/json")
public MyObject findByUuid(
        @PathVariable("uuid") String uuid) {
    ...
}

@RequestMapping(method = RequestMethod.POST, value = "/findByStringPropertyEquals", produces = "application/json")
public List<MyObject> findByStringPropertyEquals(
            @RequestParam("type") String type,
            @RequestParam("property") String property,
            @RequestParam("value") String value) {
    ...
}

现在,当我尝试测试第二种方法时,如

 mvc.perform(get("/findByStringPropertyEquals?type={0}&property={1}&value={2}", "Person", "testPropInt", 42))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)));

然后MockMvc遗憾地选择了findByUuid控制器方法。输出

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/v1/domain-entities/findByStringPropertyEquals
       Parameters = {type=[Person], property=[testPropInt], value=[42]}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.example.MyObjectController
           Method = public com.example.MyObject com.example.MyObjectController.findByUuid(java.lang.String)

但是,在Web服务器启动时定期访问REST API工作正常。 这是一个错误还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

在您的代码中,您正在调用 GET

mvc.perform(get("/findByStringPropertyEquals?type={0}&property={1}&value={2}", "Person", "testPropInt", 42))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)));

但是, POST 声明了findByStringPropertyEquals方法,因此您的代码无法使用GET解决该方法。我不确定为什么MockMVC层选择了findByUuid(也许是因为这是这个控制器上唯一的GET方法)但是你的代码没有命中findByStringPropertyEquals的原因是你选择了错误的HTTP方法。

请尝试mvc.perform(post(...))