Created
November 30, 2010 16:51
-
-
Save searls/721959 to your computer and use it in GitHub Desktop.
A handy matcher allowing you to assert that a bean is JSR-303 compliant. Usage might look like: `assertThat(beanUnderTest,is(valid));`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pillartechnology.matchers; | |
import java.util.HashSet; | |
import java.util.Set; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import org.hamcrest.Description; | |
import org.hamcrest.Factory; | |
import org.hamcrest.Matcher; | |
import org.hamcrest.TypeSafeMatcher; | |
public class ValidationMatcher extends TypeSafeMatcher<Object> { | |
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); | |
private Set<String> validationMessages = new HashSet<String>(); | |
@Override | |
public boolean matchesSafely(Object bean) { | |
Set<ConstraintViolation<Object>> violations = validator.validate(bean); | |
for (ConstraintViolation<Object> constraintViolation : violations) { | |
validationMessages.add(constraintViolation.getPropertyPath().toString() + " " + constraintViolation.getMessage()); | |
} | |
return violations.size() == 0; | |
} | |
public void describeTo(Description description) { | |
description.appendText("invalid with errors: "); | |
for (String msg : validationMessages) { | |
description.appendText(msg + "\n"); | |
} | |
} | |
@Factory | |
public static <T> Matcher<Object> valid() { | |
return new ValidationMatcher(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment