Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 控制器的MockMvc测试用例中出错_Java_Spring Mvc_Junit_Mockito - Fatal编程技术网

Java 控制器的MockMvc测试用例中出错

Java 控制器的MockMvc测试用例中出错,java,spring-mvc,junit,mockito,Java,Spring Mvc,Junit,Mockito,我已经为控制器层方法编写了一个jUnit测试用例,但由于预期结果不匹配,它失败了。 测试用例如下: @Test public void testGetNodeStatusCount() throws Exception { ListNodes listNodes = new ListNodes(); // ArgumentCaptor<Integer> userId = ArgumentCaptor.forClass(Integer.clas

我已经为控制器层方法编写了一个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());

    }
@测试
public void testGetNodeStatusCount()引发异常{
ListNodes ListNodes=新ListNodes();
//ArgumentCaptor用户标识=ArgumentCaptor.forClass(Integer.class);
当(userManagementHelper.getNodeStatusCount(0))。然后返回(
新的ResponseEntity(listNodes,新的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);
    } 
@RequestMapping(value=“/nodestatus”,method=RequestMethod.GET,products=MediaType.APPLICATION\u JSON\u value)
@应答器
公共响应性getNodeStatusCount(@RequestParam(“userId”)int userId){
返回userManagementHepler.getNodeStatusCount(userId);
} 
故障信息为:

我没有得到的是,如果设置了状态OK,那么我得到的是400而不是200


还有一件事我对“Controller”的MockMVC测试还不熟悉,所以请向我推荐一个了解这一点的来源。

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

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

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

谢谢你的回答,你能给我推荐一个了解所有这些的来源吗抱歉,我特意没有添加任何链接,因为这些链接会随着时间的推移而改变。你的方法是正确的,如果你在谷歌上搜索“mockMvc教程”,你会发现很多链接。mockMvc中唯一稍微有点棘手的事情是异步测试,因为您的控制器不是异步的,所以应该可以