gpt4 book ai didi

java - 为什么 Rest API 删除调用会收到 400 状态代码

转载 作者:行者123 更新时间:2023-11-30 06:16:50 25 4
gpt4 key购买 nike

我正在尝试使用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());
}

最佳答案

您的方法需要额外的参数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

关于java - 为什么 Rest API 删除调用会收到 400 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49007568/

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