使用 Spring Boot,我想测试我的 @RestController,一切都很好,除了当我尝试使用 @PathParam 测试请求映射时。
这涉及持有请求映射注释的接口(interface)(在本例中为 TestController)!如果我删除界面一切都很好......似乎是一个问题......
我的 Controller :
public interface TestController {
@RequestMapping(value = "/bar/{foo}/baz", method = RequestMethod.GET)
String test(@PathVariable("foo") String foo);
@RestController
class TestControllerImpl implements TestController {
@Override
public String test(String foo) {
return foo;
}
}
}
我的测试:
@Test
public void notworkingtest() throws Exception {
//THIS TEST SHOULD WORK, BUT DON'T ...
final MockMvc mockMvc = ...
mockMvc.perform(get("/bar/{foo}/baz", "foovalue") // Or get("/bar/foovalue/baz")
.contentType("text/plain"))
.andExpect(status().is2xxSuccessful())
.andExpect(content().string("foovalue"));
}
@Test
public void strangeworkingtest() throws Exception {
//THIS TEST WORKS, BUT WHY ?!?
final MockMvc mockMvc = ...
mockMvc.perform(get("/bar/{foo}/baz", "WhatEverValue")
.param("foo", "foovalue") // This param should be useless ...
.contentType("text/plain"))
.andExpect(status().is2xxSuccessful())
.andExpect(content().string("foovalue"));
}
当我有 .param("foo","foovalue) 并保留 get("/bar/{foo}/baz", "WhatEverValue") ...时,第二个测试正在工作......
如果我删除 Controller 的接口(interface),它就可以工作......
谁能给我解释一下吗?
谢谢
最佳答案
这里有两种方法:
更改端点的 URL:
@RequestMapping(value = "/test", method = RequestMethod.GET) mockMvc.perform(get("/test") .param("foo", "Value")) .andExpect(status().is2xxSuccessful()) .andExpect(content().string("foovalue"));
使用正确的 URL 调用您的端点:
mockMvc.perform(get("/user/1568/delete")) .andExpect(status().is2xxSuccessful()) .andExpect(content().string("foovalue"));
关于java - Spring Boot MockMvc 无法使用 @PathVariable 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996088/