Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.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
Spring 确保MockMvc.perform.hasErrors_Spring_Mockito - Fatal编程技术网

Spring 确保MockMvc.perform.hasErrors

Spring 确保MockMvc.perform.hasErrors,spring,mockito,Spring,Mockito,对于hasErrors,我需要以下内容返回true: mockMvc.perform(post("/user_save")) .andExpect(status().isOk()) .andExpect(model().hasErrors()); } 我通过调用userController.saveUser找到了一种方法: BindingResult mockBindingResult = mock(BindingResult.class);

对于hasErrors,我需要以下内容返回true:

mockMvc.perform(post("/user_save"))
            .andExpect(status().isOk())
            .andExpect(model().hasErrors());
}
我通过调用userController.saveUser找到了一种方法:

BindingResult mockBindingResult = mock(BindingResult.class);
    FieldError mockFieldError = mock(FieldError.class);

    when(mockBindingResult.hasErrors()).thenReturn(true);
    when(mockBindingResult.getFieldError()).thenReturn(mockFieldError);
    when(mockFieldError.getField()).thenReturn("mock error field");
    when(mockFieldError.getCode()).thenReturn("mock error code");

    User user = new User();
    String str = "test";
    user.setUsername(str);
    user.setPassword(str);
    user.setName(str);

    String result = userController.saveUser(user, mockBindingResult);
然而,这是很长的,看起来很可怕,只有通过重定向结果间接地让我看到是否有错误,如果有错误,重定向结果将采用不同的值


当然有办法调整mockM的第一个解决方案?

测试没有意义。无论控制器中发生什么,BindingResult.hasErrors都将始终生成true。你想测试什么?嗯,没有。我的控制器有if bindingResult.hasErrors,它仅在有错误时执行。至于测试,如果有错误,将重定向用户,因此我只需要检查当hasErrors返回true时是否执行了重定向和其他一些步骤。当前它返回false。您可以传递一个无效用户,并使用andReturn返回的MockMvcResult检查视图名称。