Guest User

Untitled

a guest
Jul 16th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. package com.pillartechnology.matchers;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. import javax.validation.ConstraintViolation;
  7. import javax.validation.Validation;
  8. import javax.validation.Validator;
  9.  
  10. import org.hamcrest.Description;
  11. import org.hamcrest.Factory;
  12. import org.hamcrest.Matcher;
  13. import org.hamcrest.TypeSafeMatcher;
  14.  
  15. public class ValidationMatcher extends TypeSafeMatcher<Object> {
  16.  
  17. private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
  18.  
  19. private Set<String> validationMessages = new HashSet<String>();
  20.  
  21. @Override
  22. public boolean matchesSafely(Object bean) {
  23. Set<ConstraintViolation<Object>> violations = validator.validate(bean);
  24. for (ConstraintViolation<Object> constraintViolation : violations) {
  25. validationMessages.add(constraintViolation.getPropertyPath().toString() + " " + constraintViolation.getMessage());
  26. }
  27. return violations.size() == 0;
  28. }
  29.  
  30. public void describeTo(Description description) {
  31. description.appendText("invalid with errors: ");
  32. for (String msg : validationMessages) {
  33. description.appendText(msg + "\n");
  34. }
  35. }
  36.  
  37. @Factory
  38. public static <T> Matcher<Object> valid() {
  39. return new ValidationMatcher();
  40. }
  41. }
Add Comment
Please, Sign In to add comment