@Test public void handleMethodArgumentNotValid() throws Exception { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(new TestBean(), "testBean"); errors.rejectValue("name", "invalid"); MethodParameter parameter = new MethodParameter(this.getClass().getMethod("handle", String.class), 0); MethodArgumentNotValidException ex = new MethodArgumentNotValidException(parameter, errors); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); assertNotNull("No ModelAndView returned", mav); assertTrue("No Empty ModelAndView returned", mav.isEmpty()); assertEquals("Invalid status code", 400, response.getStatus()); }
@Test public void withErrors() throws Exception { this.tag.setPath("name"); this.tag.setCssClass("good"); this.tag.setCssErrorClass("bad"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME); errors.rejectValue("name", "some.code", "Default Message"); errors.rejectValue("name", "too.short", "Too Short"); exposeBindingResult(errors); assertEquals(Tag.SKIP_BODY, this.tag.doStartTag()); String output = getOutput(); assertTagOpened(output); assertTagClosed(output); assertContainsAttribute(output, "type", getType()); assertValueAttribute(output, "Rob"); assertContainsAttribute(output, "class", "bad"); }
@Test public void testRejectWithoutDefaultMessage() { TestBean tb = new TestBean(); tb.setName("myName"); tb.setAge(99); BeanPropertyBindingResult ex = new BeanPropertyBindingResult(tb, "tb"); ex.reject("invalid"); ex.rejectValue("age", "invalidField"); StaticMessageSource ms = new StaticMessageSource(); ms.addMessage("invalid", Locale.US, "general error"); ms.addMessage("invalidField", Locale.US, "invalid field"); assertEquals("general error", ms.getMessage(ex.getGlobalError(), Locale.US)); assertEquals("invalid field", ms.getMessage(ex.getFieldError("age"), Locale.US)); }
public Errors checkConstraints(Object target, Class<?>...groups) { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(target, target.getClass().getSimpleName()); Set<ConstraintViolation<Object>> result = this.beanValidator.validate(target, groups); for (ConstraintViolation<Object> violation : result) { String field = violation.getPropertyPath().toString(); FieldError fieldError = errors.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { errors.rejectValue(field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint(errors.getObjectName(), field, violation.getConstraintDescriptor()), violation.getMessage()); } } return errors; } }