我有以下控制器方法。用户提交带有4个输入字段的搜索表单,并且必须填写至少一个字段。如果所有字段都为空(使用验证器),则表单顶部(在同一页面中)将显示错误。
否则,它将使用服务方法查找用户并在表单底部显示结果(在同一页面中)。这就是为什么在if语句中我返回相同的页面以及方法的结尾,因为无论发生什么,用户都被定向到同一页面
@RequestMapping(value="/search", method={RequestMethod.POST})
public ModelAndView searchUser(@ModelAttribute("searchUserDTO")SearchUserDTO searchUserDTO, BindingResult bindingResult, ModelMap modelMap){
validate(searchUserDTO, bindingResult);
List<BlueUser> users = new ArrayList<>();
if (bindingResult.hasErrors()) {
modelMap.put("searchUserDTO", searchUserDTO);
return new ModelAndView(VIEW_USERS, modelMap);
} else {
users = BlueUserService.findUsers(searchUserDTO.getMyName, searchUserDTO.getSSID(), searchUserDTO.getPostcode(), new Email(searchUserDTO.getMail()));
}
modelMap.put("searchUserDTO", users);
return new ModelAndView(VIEW_USERS, modelMap);
}
验证方法
@Override
public void validate(Object target, Errors errors) {
SearchUserDTO dto = (SearchUserDTO)target;
if(dto.getMyName()==null && dto.getSSID() == null && dto.getPostcode() == null && dto.getMail()==null){
errors.reject(EMPTY, "Please fill in the form");
}
}
我使用reject
在全局范围内返回错误,而不是在特定字段和以下测试方法中返回错误:
public static final String BINDING_RESULT = BindingResult.class.getName() + '.' + "searchUserDTO";
@Test
public void searchUserPOST() throws Exception{
MultiValueMap<String, String> paramMap = mockMVCTestUtil.createParamMap("myName", null,
"ssid", null,
"postcode", null,
"mail", null);
MvcResult mvcResult = this.mockMvc.perform(
post("/search")
.params(paramMap))
.andExpect(model().attributeExists("searchUserDTO"))
.andExpect(model().attributeHasErrors("searchUserDTO"))
.andExpect(status().isOk())
.andExpect(redirectedUrl(VIEW_USERS))
.andExpect(forwardedUrl(VIEW_USERS))
.andReturn();
BindingResult bindingResult = (BindingResult) mvcResult.getModelAndView().getModel().get(BINDING_RESULT);
assertNotNull(bindingResult);
assertGlobalErrorMessage(bindingResult, "Please fill in the form");
}
当我运行测试方法时,它失败了,我收到以下错误消息:
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: No errors for attribute 'searchUserDTO'
我做错了什么?