java类org.springframework.validation.BeanPropertyBindingResult的实例源码

SiteOptionTests.java 文件源码 项目:nixmash-blog 阅读 42 收藏 0 点赞 0 评论 0
@Test
public void SiteOptionMapDtoValidationTests() {

    SiteOptionMapDTO siteOptionMapDTO = SiteOptionMapDTO.withGeneralSettings(
            null,
            siteOptions.getSiteDescription(),
            siteOptions.getAddGoogleAnalytics(),
            siteOptions.getGoogleAnalyticsTrackingId(),
            siteOptions.getUserRegistration())
            .build();

    Errors errors = new BeanPropertyBindingResult(siteOptionMapDTO, "siteOptionMapDTO");
    ValidationUtils.invokeValidator(new SiteOptionMapDtoValidator(), siteOptionMapDTO, errors);
    assertTrue(errors.hasFieldErrors("siteName"));
    assertEquals("EMPTY", errors.getFieldError("siteName").getCode());

}
BlogValidationTests.java 文件源码 项目:SpringMvcBlog 阅读 31 收藏 0 点赞 0 评论 0
@Test
public void testValidationError(){
    Blog blog = new Blog(){
        {
            setBlogName("te");
            setBlogUrl("Test Blog");
        }
    };

    Errors errors = new BeanPropertyBindingResult(blog, "blog");
    blogValidation.validate(blog, errors);
    assertTrue(errors.hasErrors());
    assertTrue( errors.getErrorCount() == 1 );
    assertEquals("Blog ad\u0131 en az �� karekter olmal\u0131.", 
            getConfiguredMessage(errors.getFieldError("BlogName")));

}
PayloadArgumentResolver.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param message the currently processed message
 * @param parameter the method parameter
 * @param target the target payload object
 * @throws MethodArgumentNotValidException in case of binding errors
 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
    if (this.validator == null) {
        return;
    }
    for (Annotation ann : parameter.getParameterAnnotations()) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
            Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
            BeanPropertyBindingResult bindingResult =
                    new BeanPropertyBindingResult(target, getParameterName(parameter));
            if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
                ((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
            }
            else {
                this.validator.validate(target, bindingResult);
            }
            if (bindingResult.hasErrors()) {
                throw new MethodArgumentNotValidException(message, parameter, bindingResult);
            }
            break;
        }
    }
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 46 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidation() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(2, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    List<String> errorCodes = Arrays.asList(fieldError.getCodes());
    assertEquals(4, errorCodes.size());
    assertTrue(errorCodes.contains("NotNull.person.name"));
    assertTrue(errorCodes.contains("NotNull.name"));
    assertTrue(errorCodes.contains("NotNull.java.lang.String"));
    assertTrue(errorCodes.contains("NotNull"));
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    errorCodes = Arrays.asList(fieldError.getCodes());
    assertEquals(5, errorCodes.size());
    assertTrue(errorCodes.contains("NotNull.person.address.street"));
    assertTrue(errorCodes.contains("NotNull.address.street"));
    assertTrue(errorCodes.contains("NotNull.street"));
    assertTrue(errorCodes.contains("NotNull.java.lang.String"));
    assertTrue(errorCodes.contains("NotNull"));
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 44 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 40 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithErrorInListElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressList().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressList[0].street");
    assertEquals("addressList[0].street", fieldError.getField());
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 38 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithErrorInSetElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressSet().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressSet[].street");
    assertEquals("addressSet[].street", fieldError.getField());
}
MarshallingViewTests.java 文件源码 项目:spring4-understanding 阅读 38 收藏 0 点赞 0 评论 0
@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
    Object toBeMarshalled = new Object();
    String modelKey = "key";
    Map<String, Object> model = new LinkedHashMap<String, Object>();
    model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey));
    model.put(modelKey, toBeMarshalled);

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();

    given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true);
    given(marshallerMock.supports(Object.class)).willReturn(true);

    view.render(model, request, response);
    assertEquals("Invalid content type", "application/xml", response.getContentType());
    assertEquals("Invalid content length", 0, response.getContentLength());
    verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
InputTagTests.java 文件源码 项目:spring4-understanding 阅读 57 收藏 0 点赞 0 评论 0
@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");
}
InputTagTests.java 文件源码 项目:spring4-understanding 阅读 48 收藏 0 点赞 0 评论 0
@Test
public void withCustomBinder() throws Exception {
    this.tag.setPath("myFloat");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", getType());
    assertValueAttribute(output, "12.34f");
}
RadioButtonTagTests.java 文件源码 项目:spring4-understanding 阅读 29 收藏 0 点赞 0 评论 0
@Test
public void withCheckedObjectValueAndEditor() throws Exception {
    this.tag.setPath("myFloat");
    this.tag.setValue("F12.99");

    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    MyFloatEditor editor = new MyFloatEditor();
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(Float.class, editor);
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);
    assertContainsAttribute(output, "name", "myFloat");
    assertContainsAttribute(output, "type", "radio");
    assertContainsAttribute(output, "value", "F" + getFloat().toString());
    assertContainsAttribute(output, "checked", "checked");
}
HiddenInputTagTests.java 文件源码 项目:spring4-understanding 阅读 35 收藏 0 点赞 0 评论 0
@Test
public void withCustomBinder() throws Exception {
    this.tag.setPath("myFloat");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();

    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", "hidden");
    assertContainsAttribute(output, "value", "12.34f");
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 65 收藏 0 点赞 0 评论 0
@Test
public void withExplicitNonWhitespaceBodyContent() throws Exception {
    String mockContent = "This is some explicit body content";
    this.tag.setBodyContent(new MockBodyContent(mockContent, getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);
    assertEquals(mockContent, getOutput());
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 44 收藏 0 点赞 0 评论 0
@Test
public void withExplicitWhitespaceBodyContent() throws Exception {
    this.tag.setBodyContent(new MockBodyContent("\t\n   ", getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "Default Message");
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 54 收藏 0 点赞 0 评论 0
@Test
public void withExplicitEmptyWhitespaceBodyContent() throws Exception {
    this.tag.setBodyContent(new MockBodyContent("", getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "Default Message");
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
@Test
public void withErrors() throws Exception {
    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "<br/>");
    assertBlockTagContains(output, "Default Message");
    assertBlockTagContains(output, "Too Short");
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 40 收藏 0 点赞 0 评论 0
@Test
public void withEscapedErrors() throws Exception {
    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default <> Message");
    errors.rejectValue("name", "too.short", "Too & Short");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "<br/>");
    assertBlockTagContains(output, "Default &lt;&gt; Message");
    assertBlockTagContains(output, "Too &amp; Short");
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 51 收藏 0 点赞 0 评论 0
@Test
public void asBodyTag() throws Exception {
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 44 收藏 0 点赞 0 评论 0
@Test
public void asBodyTagWithExistingMessagesAttribute() throws Exception {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
/**
 * https://jira.spring.io/browse/SPR-2788
 */
@Test
public void asBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, PageContext.APPLICATION_SCOPE);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertEquals(existingAttribute,
            getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, PageContext.APPLICATION_SCOPE));
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 41 收藏 0 点赞 0 评论 0
/**
 * https://jira.spring.io/browse/SPR-4005
 */
@Test
public void omittedPathMatchesObjectErrorsOnly() throws Exception {
    this.tag.setPath(null);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.reject("some.code", "object error");
    errors.rejectValue("name", "some.code", "field error");
    exposeBindingResult(errors);
    this.tag.doStartTag();
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    this.tag.doEndTag();
    String output = getOutput();
    assertTrue(output.contains("id=\"testBean.errors\""));
    assertTrue(output.contains("object error"));
    assertFalse(output.contains("field error"));
}
ErrorsTagTests.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
private void assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(int scope) throws JspException {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, scope);

    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertEquals(0, output.length());

    assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, scope));
}
CheckboxTagTests.java 文件源码 项目:spring4-understanding 阅读 33 收藏 0 点赞 0 评论 0
@Test
public void withSingleValueAndEditor() throws Exception {
    this.bean.setName("Rob Harrop");
    this.tag.setPath("name");
    this.tag.setValue("   Rob Harrop");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, new StringTrimmerEditor(false));
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element checkboxElement = (Element) document.getRootElement().elements().get(0);
    assertEquals("input", checkboxElement.getName());
    assertEquals("checkbox", checkboxElement.attribute("type").getValue());
    assertEquals("name", checkboxElement.attribute("name").getValue());
    assertEquals("checked", checkboxElement.attribute("checked").getValue());
    assertEquals("   Rob Harrop", checkboxElement.attribute("value").getValue());
}
SelectTagTests.java 文件源码 项目:spring4-understanding 阅读 40 收藏 0 点赞 0 评论 0
@Test
public void withListAndTransformTagAndEditor() throws Exception {
    this.tag.setPath("realCountry");
    this.tag.setItems(Country.getCountries());
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();

    TransformTag transformTag = new TransformTag();
    transformTag.setValue(Country.getCountries().get(0));
    transformTag.setVar("key");
    transformTag.setParent(this.tag);
    transformTag.setPageContext(getPageContext());
    transformTag.doStartTag();
    assertEquals("Austria", getPageContext().findAttribute("key"));
}
SelectTagTests.java 文件源码 项目:spring4-understanding 阅读 38 收藏 0 点赞 0 评论 0
@Test
public void withListAndEditor() throws Exception {
    this.tag.setPath("realCountry");
    this.tag.setItems(Country.getCountries());
    this.tag.setItemValue("isoCode");
    this.tag.setItemLabel("name");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();
    String output = getOutput();
    assertTrue(output.startsWith("<select "));
    assertTrue(output.endsWith("</select>"));
    assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
SelectTagTests.java 文件源码 项目:spring4-understanding 阅读 40 收藏 0 点赞 0 评论 0
@Test
public void nestedPathWithListAndEditor() throws Exception {
    this.tag.setPath("bean.realCountry");
    this.tag.setItems(Country.getCountries());
    this.tag.setItemValue("isoCode");
    this.tag.setItemLabel("name");
    TestBeanWrapper testBean = new TestBeanWrapper();
    testBean.setBean(getTestBean());
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(testBean , "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();
    String output = getOutput();
    assertTrue(output.startsWith("<select "));
    assertTrue(output.endsWith("</select>"));
    assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
ModelResultMatchersTests.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
@Before
public void setUp() throws Exception {
    this.matchers = new ModelResultMatchers();

    ModelAndView mav = new ModelAndView("view", "good", "good");
    BindingResult bindingResult = new BeanPropertyBindingResult("good", "good");
    mav.addObject(BindingResult.MODEL_KEY_PREFIX + "good", bindingResult);

    this.mvcResult = getMvcResult(mav);

    Date date = new Date();
    BindingResult bindingResultWithError = new BeanPropertyBindingResult(date, "date");
    bindingResultWithError.rejectValue("time", "error");

    ModelAndView mavWithError = new ModelAndView("view", "good", "good");
    mavWithError.addObject("date", date);
    mavWithError.addObject(BindingResult.MODEL_KEY_PREFIX + "date", bindingResultWithError);

    this.mvcResultWithError = getMvcResult(mavWithError);
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();

    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 88 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithAutowiredValidator() throws Exception {
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
            LocalValidatorFactoryBean.class);
    LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

    ValidPerson person = new ValidPerson();
    person.expectsAutowiredValidator = true;
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
    ctx.close();
}
ValidatorFactoryTests.java 文件源码 项目:spring4-understanding 阅读 59 收藏 0 点赞 0 评论 0
@Test
public void testSpringValidationWithErrorInListElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();

    ValidPerson person = new ValidPerson();
    person.getAddressList().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressList[0].street");
    assertEquals("addressList[0].street", fieldError.getField());
}


问题


面经


文章

微信
公众号

扫码关注公众号