Created
February 27, 2017 16:11
-
-
Save m-x-k/b00da4a6f1136055a42dd8866638ab41 to your computer and use it in GitHub Desktop.
JUnit validate JSR-303 with assertion
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
import org.hibernate.validator.constraints.NotEmpty; | |
import org.junit.BeforeClass; | |
import org.junit.Test; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import javax.validation.ValidatorFactory; | |
import java.util.Set; | |
import static org.junit.Assert.assertEquals; | |
import static org.junit.Assert.assertTrue; | |
public class JSRValidationTest { | |
private static Validator validator; | |
@BeforeClass | |
public static void setUp() { | |
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); | |
validator = factory.getValidator(); | |
} | |
@Test | |
public void myObject_NotNull_Test() { | |
MyObject myObject = new MyObject(null); | |
Set<ConstraintViolation<MyObject>> violations = validator.validate(myObject); | |
assertConstraint(violations, ConstraintValidationTypes.MAY_NOT_BE_EMPTY); | |
} | |
protected <T> void assertConstraint(Set<ConstraintViolation<T>> violations, ConstraintValidationTypes... constraintValidationTypes) { | |
for (ConstraintValidationTypes validation: constraintValidationTypes) { | |
String expected = validation.getMessage(); | |
assertTrue(String.format("Missing: %s", expected), violations.stream().anyMatch(t -> t.getMessage().equals(expected))); | |
} | |
assertEquals(constraintValidationTypes.length, violations.size()); | |
} | |
} | |
class MyObject { | |
@NotEmpty | |
private String value; | |
public MyObject(String value) { | |
this.value = value; | |
} | |
} | |
enum ConstraintValidationTypes { | |
MAY_NOT_BE_NULL("may not be null"), | |
MAY_NOT_BE_EMPTY("may not be empty"); | |
private String message; | |
ConstraintValidationTypes(String message) { | |
this.message = message; | |
} | |
public String getMessage() { | |
return message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment