我有一个包含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工作正常。 这是一个错误还是我做错了什么?
答案 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(...))
。