MethodArgumentNotValidExceptionHandler implements BaseExceptionHandler<MethodArgumentNotValidException> { @ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) @ExceptionHandler(value = { MethodArgumentNotValidException.class }) @ResponseBody @Override public MessageResource handle(final MethodArgumentNotValidException e) throws Exception { LOGGER.error("Handling validation exception", e); BindingResult bindingResult = e.getBindingResult(); List<FieldError> fieldErrors = bindingResult.getFieldErrors(); List<Pair<String, String>> errors = new ArrayList<Pair<String, String>>(); for (FieldError error : fieldErrors) { Pair<String, String> pair = new Pair<String, String>(); pair.setName(error.getField()); pair.setValue(error.getDefaultMessage()); errors.add(pair); } return new ValidationMessageResource(MessageType.ERROR, "Validation failed, please see following errors", errors); }  @ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) @ExceptionHandler(value = { MethodArgumentNotValidException.class }) @ResponseBody @Override MessageResource handle(final MethodArgumentNotValidException e);  }
@Test public void testHandle() throws Exception { MethodArgumentNotValidException e = new MethodArgumentNotValidException(parameter, bindingResult ); String field = "name"; String defaultMessage = "not valid"; FieldError fieldError1 = new FieldError("fdsfsd", field, defaultMessage); List<FieldError> errors = Arrays.asList(fieldError1); Pair<String, String> pair = new Pair<String, String>(); pair.setName(field); pair.setValue(defaultMessage); List<Pair<String, String>> errorResource = Arrays.asList(pair); MessageResource expected = new ValidationMessageResource(MessageType.ERROR, "Validation failed, please see following errors", errorResource ); when(bindingResult.getFieldErrors()).thenReturn(errors); MessageResource actual = unit.handle(e); assertEquals(expected, actual); }
@Test public void testHandleWithEmptyErrors() throws Exception { MethodArgumentNotValidException e = new MethodArgumentNotValidException(parameter, bindingResult ); List<Pair<String, String>> errorResource = Collections.emptyList(); MessageResource expected = new ValidationMessageResource(MessageType.ERROR, "Validation failed, please see following errors", errorResource ); when(bindingResult.getFieldErrors()).thenReturn(Collections.<FieldError>emptyList()); MessageResource actual = unit.handle(e); assertEquals(expected, actual); }