Junit MockMvc使用URL返回404中的路径变量执行POST

问题描述 投票:1回答:1

我在控制器中有一个具有此方法的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();  
 }

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

MockHttpServletRequest:

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

有人可以让我知道为什么我找不到404吗?谢谢。

java spring-boot junit mockmvc
1个回答
2
投票

docs开始,您需要在课堂上@AutoConfigureMockMvc@Autowire MockMvc

另一种有用的方法是根本不启动服务器,而仅测试其下面的层,Spring在该层处理传入的HTTP请求并将其交给您的控制器。这样,几乎将使用整个堆栈,并且将以完全相同的方式调用您的代码,就像处理真实的HTTP请求一样,而无需启动服务器。为此,我们将使用Spring的MockMvc,我们可以通过在测试用例上使用@AutoConfigureMockMvc注释来要求将其注入:

代码:

@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();  
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.