我试图覆盖BindingResult中的默认错误消息。我实施了这样的控制器建议
@ControllerAdvice
public final class DefaultControllerAdvice {
private static final String ERROR_MESSAGE_FORMATTER = " - ";
@ExceptionHandler(BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public List<String> handleValidationException(final BindException exception) {
return exception.getBindingResult()
.getAllErrors()
.stream()
.filter(error -> error instanceof FieldError)
.map(objectError -> (FieldError) objectError)
.map(errorMessageFormatter)
.collect(Collectors.toList());
}
private final Function<FieldError, String> errorMessageFormatter =
error -> error.getField() + ERROR_MESSAGE_FORMATTER + error.getDefaultMessage();
}
和我的控制器
@PostMapping(value = "/register")
private String postRegistration( @ModelAttribute @Valid final UserCreateFormDto user, final BindingResult result,
final RedirectAttributes redirectAttributes, final WebRequest webRequest) {
try {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.user", result);
redirectAttributes.addFlashAttribute("user", user);
throw new BindException(result);
}
if (userService.checkEmailExist(user.getEmail())) {
throw new UserNotExistsException("User with email: "+ user.getEmail()+" already exists.");
}
final User registered = userService.createNewUserAccount(user);
final String appUrl = webRequest.getContextPath();
eventPublisher.publishEvent(
new RegistrationCompleteEvent(registered, webRequest.getLocale(), appUrl));
return "redirect:/login?success";
} catch (UserNotExistsException error) {
return "redirect:/register?exists";
} catch (BindException error) {
return "redirect:/register";
}
}
和测试用例
@Test
public void shouldNotCreateUserWhenUsernameIsEmpty() throws Exception {
//given
final UserCreateFormDto userCreateFormDto = createUserCreateForm();
final User user = createUser();
given(userService.checkEmailExist(userCreateFormDto.getEmail())).willReturn(false);
given(userService.createNewUserAccount(any(UserCreateFormDto.class))).willReturn(user);
//when
final MvcResult response = mockMvc
.perform(post("/register").with(csrf())
.contentType(MediaType.MULTIPART_FORM_DATA)
.param("username","")
.param("email",userCreateFormDto.getEmail())
.param("password", Arrays.toString(userCreateFormDto.getPassword()))
.param("matchingPassword", Arrays.toString(userCreateFormDto.getMatchingPassword())))
.andReturn();
//then
assertThat(response.getFlashMap().isEmpty()).isFalse();
assertThat(response.getResponse().getStatus()).isEqualTo(HttpStatus.FOUND.value());
assertThat(response.getResponse().getRedirectedUrl()).isEqualTo("/register");
verify(userService, times(1)).checkEmailExist(userCreateFormDto.getEmail());
verify(userService, times(0)).createNewUserAccount(any(UserCreateFormDto.class));
我的问题是如何获取bindingResult默认错误消息? 我想测试在验证输入字段时得到的错误消息。