为什么我会获得Rest API删除调用的400状态代码

时间:2018-02-27 11:25:56

标签: java rest junit mockito

我正在尝试使用mockito模拟Rest API调用。很多次我尝试执行以下测试用例时失败,并带有以下状态代码:400

我检查了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);
}

以下是测试电话

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

1 个答案:

答案 0 :(得分:1)

您的方法需要额外的参数reason,您在测试方法中未提供 mockMvc 请求。

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

将它交给mockMvc

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

或将其标记为“不需要”

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