【发布时间】:2020-03-12 00:53:19
【问题描述】:
我有一个 SpringBoot 应用程序,在控制器中使用此方法在数据库中创建用户。控制器在 Postman 中运行良好。
@RestController
@RequestMapping("/v1")
public class UserController {
@PostMapping(value = "/user/{id}")
public void createUser(@PathVariable Integer id, @Valid @RequestBody User request,
BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
throw new RequestValidationException(VALIDATION_ERRORS, bindingResult.getFieldErrors());
}
userService.createUser(id, request), HttpStatus.CREATED);
}
现在我有一个 junit 测试用例来测试这个方法,我得到一个 404
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
public class UserTest {
private MockMvc mockMvc;
final String CREATE_USER_URL = "/v1/user/" + "10";
private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testCreateUser() throws Exception {
mockMvc.perform(post(CREATE_USER_URL)
// doesn't work either if I put "/v1/user/10" or post("/v1/user/{id}", 10) here
.content(TestUtils.toJson(request, false))
.contentType(contentType))
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
}
但在日志中,我能够看到正确的 url:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /v1/user/10
Parameters = {}
有人可以告诉我为什么我会收到 404 NOT Found 吗?谢谢。
【问题讨论】:
-
你能展示完整的测试类吗?
-
@Deadpool 已更新。谢谢
-
你能发布整个控制器的代码吗?我觉得您缺少将控制器级别的 @RequestMapping 的一部分添加到您的 URL
-
@HirenShah 已更新。谢谢。
标签: java spring-boot junit mockmvc