gpt4 book ai didi

java - Junit MockMvc 使用 URL 中的路径变量执行 POST 返回 404 未找到

转载 作者:行者123 更新时间:2023-11-30 01:43:59 25 4
gpt4 key购买 nike

我有一个 SpringBoot 应用程序,在 Controller 中使用此方法在数据库中创建用户。 Controller 在 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();
}

但是在日志中,我能够看到正确的网址:

MockHttpServletRequest:

  HTTP Method = POST
Request URI = /v1/user/10
Parameters = {}

有人可以告诉我为什么我收到 404 NOT Found 吗?谢谢。

最佳答案

来自docs您需要在类上使用 @AutoConfigureMockMvc@Autowire MockMvc

Another useful approach is to not start the server at all, but test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost the full stack is used, and your code will be called exactly the same way as if it was processing a real HTTP request, but without the cost of starting the server. To do that we will use Spring’s MockMvc, and we can ask for that to be injected for us by using the @AutoConfigureMockMvc annotation on the test case:

代码:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserTest {

@Autowire
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();
}
}

关于java - Junit MockMvc 使用 URL 中的路径变量执行 POST 返回 404 未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com