I'm trying to write a jUnit test for a bean validation. I read How to test validation annotations of a class using JUnit? and wrote a test code like as below.
My environment:
- Sprint Boot 2.2.6
- Java11
- AssertJ 3.15.0
Target Bean class:
public class Customer {
@NotEmpty
private String name;
@Min(18)
private int age;
// getter and setter
}
JUnit test code:
public class CustomerValidationTest {
private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
@Test
public void test() {
Customer customer = new Customer(null, 18);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertThat(violations.size()).isEqualTo(1); // check violations count
// check which constraints are violated by the message of the violation
assertThat(violations).extracting("message").containsOnly("must not be empty");
}
}
I'd like to check which constraints are violated. For now, I check the message of violations. Is there better way?