I want to validate an entity using bean validation in a JUnit test. The setup seems fine but the test doesn’t fail as it should. Hence, it looks like the entity isn’t validated properly.
Here’s the relevant JPA annotation:
@Column(name = "mobile_numbers", table = STN)
private String smsRecipientMobileNumbers;
The column gets a default size of 255 chars (is applied correctly in database).
Here’s the test:
final Collection<String> recipients = new ArrayList<String>(2000);
for (int i = 0; i < 2000; i++) {
recipients.add("some mobile number");
}
objectUnderTest.setSmsRecipients(recipients);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
violations = validator.validate(objectUnderTest, Default.class);
assertThat(violations, is(empty()));
}
I expect it to fail because the smsRecipientMobileNumbers is way beyond 255 chars but it passes.
If I explicitly apply a size constraint in the entity the test fails:
@Column(name = "mobile_numbers", table = STN)
@Size(max = 255)
private String smsRecipientMobileNumbers;
What am I doing wrong here? Obviously the chosen provider must be able interpret the JPA annotations correctly. The validator is an instance of org.hibernate.validator.engine.ValidatorImpl.
Bean Validation does not take JPA entities (or default column sizes) into account. If you want to validate the length using Bean Validation, you have to add the
@Sizeconstraint.JPA providers can optionally consider the constraints when creating DDL statements, Hibernate ORM for instance should set the column length to the
maxattribute of@Size.