简体   繁体   English

为什么我会收到 400 状态代码来进行 Rest API 删除调用

[英]Why do I get 400 Status code for Rest API delete call

I am trying to mock a Rest API call using mockito.我正在尝试使用 mockito 模拟 Rest API 调用。 Many times I tried executing the below test case it fails with the following status code:400很多次我尝试执行下面的测试用例它失败并显示以下状态代码:400

I have checked the URI, the URI passed is also fine but I would like to know where I am missing.我已经检查了 URI,通过的 URI 也很好,但我想知道我在哪里丢失了。

@RequestMapping(value = "/todo/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Response> removeToDoById(@PathVariable("id") long id, @RequestParam((value = "reason") String reason) ) throws ToDoException{
    logger.info("ToDo id to remove " + id);
    ToDo toDo = toDoService.getToDoById(id);
    if (toDo == null || toDo.getId() <= 0){
        throw new ToDoException("ToDo to delete doesn´t exist");
    }
    toDoService.removeToDo(toDo);
    return new ResponseEntity<Response>(new Response(HttpStatus.OK.value(), "ToDo has been deleted"), HttpStatus.OK);
}

Below is the test call下面是测试电话

@Test
public void verifyDeleteToDo() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.delete("/todo/4").accept(MediaType.APPLICATION_JSON))
    .andExpect(jsonPath("$.status").value(200))
    .andExpect(jsonPath("$.message").value("ToDo has been deleted"))
    .andDo(print());
}

Your method requires additional parameter reason which you don't provide in request to mockMvc in your test method.您的方法需要额外的参数reason ,您没有在测试方法中向mockMvc 的请求中提供这些参数。

@RequestMapping(value = "/todo/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Response> removeToDoById(@PathVariable("id") long id, @RequestParam((value = "reason") String reason) ) throws ToDoException{

Either give it to mockMvc要么把它给mockMvc

mockMvc.perform(delete("/todo/4")
                .param("reason", "bla-bla")
                // omitted

or mark it as "not required"或将其标记为“不需要”

@RequestParam(required = false, value = "reason") String reason

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM