gpt4 book ai didi

java - Controller 的 MockMvc 测试用例中出现错误

转载 作者:行者123 更新时间:2023-11-30 07:13:14 25 4
gpt4 key购买 nike

我已经为 Controller 层方法编写了一个 jUnit 测试用例,但由于预期结果不匹配而失败。测试用例如下:

 @Test
public void testGetNodeStatusCount() throws Exception {

ListNodes listNodes = new ListNodes();
// ArgumentCaptor<Integer> userId = ArgumentCaptor.forClass(Integer.class);
when(userManagementHelper.getNodeStatusCount(0)).thenReturn(
new ResponseEntity<ListNodes>(listNodes, new HttpHeaders(),
HttpStatus.OK));

mockMvc.perform(get("/usermgmt/nodestatus")).andExpect(status().isOk());

}

编写此测试用例的方法如下:

@RequestMapping(value = "/nodestatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<ListNodes> getNodeStatusCount(@RequestParam("userId") int userId) {
return userManagementHepler.getNodeStatusCount(userId);
}

失败消息是: enter image description here

我没有得到的是,如果状态已设置确定,那么我将如何获得 400 而不是 200。

还有一件事我对“ Controller ”的 MockMVC 测试很陌生,所以请建议我一个学习这个的来源。

最佳答案

您的 Controller 需要一个必需的请求参数,这就是您收到状态 400(错误请求)的原因

您可以修改您的测试以包含此请求参数mockMvc.perform(get("/usermgmt/nodestatus?userId=0")).andExpect(status().isOk());

或者您可以将请求参数设置为可选@RequestParam(value = "userId", required = false, defaultValue = "0")

关于java - Controller 的 MockMvc 测试用例中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829532/

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