ObjectValidatorImpl implements ObjectValidator { @Override public Set<String> validate(Object object) { Set<String> errors = new HashSet<>(); Object objectWithFilters = filterProcessor.applyFilters(object); Arrays.stream(objectWithFilters.getClass().getDeclaredFields()) .forEach(f -> { try { f.setAccessible(true); Object value = f.get(objectWithFilters); getValidators().stream() .filter(v -> f.isAnnotationPresent(v.getAnnotationClass())) .forEach(v -> { Set<String> fieldErrors = validateField(v, objectWithFilters, value, f); errors.addAll(fieldErrors); }); } catch (IllegalAccessException e) { errors.add(String.format( "Failed to read field \"%s\" value", f.getName() )); } } ); return errors; }  @Override Set<String> validate(Object object);  }
@Test public void testValidObject() throws Exception { ObjectToValidate validObject = new ObjectToValidate(); validObject.setRequiredField("something"); assertThat(objectValidator.validate(validObject), is(empty())); }
@Test public void testInvalidObject() throws Exception { ObjectToValidate validObject = new ObjectToValidate(); List<String> errors = new ArrayList<>(objectValidator.validate(validObject)); assertThat(errors, hasSize(1)); assertThat(errors.get(0).contains("customName"), is(true)); }
@Test public void testValidObjectWithFilter() throws Exception { ObjectToValidateWithFilter validObjectWithFilter = new ObjectToValidateWithFilter(); assertThat(objectValidator.validate(validObjectWithFilter), is(empty())); }
@Test public void testFilterButNoValidator() throws Exception { ObjectWithFilterOnly validObjectWithFilterOnly = new ObjectWithFilterOnly(); assertThat(objectValidator.validate(validObjectWithFilterOnly), is(empty())); Object fieldValue = getFieldValue(validObjectWithFilterOnly, "fieldWithFilter"); assertThat(fieldValue, notNullValue()); assertThat(fieldValue, is(instanceOf(String.class))); assertThat(String.valueOf(fieldValue), equalTo("one, two")); }
@Test public void testObjectWithSetField() throws Exception { ObjectToValidateWithSet invalidObject = new ObjectToValidateWithSet(); assertThat(objectValidator.validate(invalidObject), hasSize(1)); }