|
35 | 35 | import javax.validation.constraints.NotNull; |
36 | 36 |
|
37 | 37 | import org.hibernate.validator.HibernateValidator; |
| 38 | +import org.junit.Ignore; |
38 | 39 | import org.junit.Test; |
39 | 40 |
|
40 | 41 | import org.springframework.validation.BeanPropertyBindingResult; |
41 | 42 | import org.springframework.validation.Errors; |
42 | 43 | import org.springframework.validation.FieldError; |
43 | 44 | import org.springframework.validation.ObjectError; |
44 | 45 |
|
| 46 | +import static org.hamcrest.Matchers.instanceOf; |
45 | 47 | import static org.junit.Assert.*; |
46 | 48 |
|
47 | 49 | /** |
@@ -102,6 +104,22 @@ public void testSimpleValidationWithClassLevel() throws Exception { |
102 | 104 | assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); |
103 | 105 | } |
104 | 106 |
|
| 107 | + @Test |
| 108 | + @Ignore |
| 109 | + public void testSpringValidationFieldType() throws Exception { |
| 110 | + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); |
| 111 | + validator.afterPropertiesSet(); |
| 112 | + ValidPerson person = new ValidPerson(); |
| 113 | + person.setName("Phil"); |
| 114 | + person.getAddress().setStreet("Phil's Street"); |
| 115 | + BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); |
| 116 | + validator.validate(person, errors); |
| 117 | + assertEquals(1, errors.getErrorCount()); |
| 118 | + assertThat("Field/Value type missmatch", |
| 119 | + errors.getFieldError("address").getRejectedValue(), |
| 120 | + instanceOf(ValidAddress.class)); |
| 121 | + } |
| 122 | + |
105 | 123 | @Test |
106 | 124 | public void testSpringValidation() throws Exception { |
107 | 125 | LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); |
@@ -289,8 +307,13 @@ public void initialize(NameAddressValid constraintAnnotation) { |
289 | 307 | } |
290 | 308 |
|
291 | 309 | @Override |
292 | | - public boolean isValid(ValidPerson value, ConstraintValidatorContext constraintValidatorContext) { |
293 | | - return (value.name == null || !value.address.street.contains(value.name)); |
| 310 | + public boolean isValid(ValidPerson value, ConstraintValidatorContext context) { |
| 311 | + boolean valid = (value.name == null || !value.address.street.contains(value.name)); |
| 312 | + if (!valid && "Phil".equals(value.name)) { |
| 313 | + context.buildConstraintViolationWithTemplate( |
| 314 | + context.getDefaultConstraintMessageTemplate()).addNode("address").addConstraintViolation().disableDefaultConstraintViolation(); |
| 315 | + } |
| 316 | + return valid; |
294 | 317 | } |
295 | 318 | } |
296 | 319 |
|
|
0 commit comments