SORMAS-Project
SORMAS-Project copied to clipboard
JUnit does not honor validation
Bug Description
When tests are executed, method arguments annotated with @Valid are not validated.
Steps to Reproduce
Take a look at this (currently skipped) test in CountryFacadeEjbTest:
@Test(expected = ConstraintViolationException.class)
public void testSaveCountryIsoCodeEmpty() {
CountryDto country = new CountryDto();
country.setDefaultName("Romania");
getCountryFacade().save(country);
}
This test should succeed b/c CountryDto has a couple of constraints which are violated and save is defined as DTO save(@Valid DTO dto) in BaseFacade, however, tests apparently do not have any validation context available.
Expected Behavior
Test does not need to be skipped and passes. Validation works in tests as it does at runtime.
Additional Information
Information on this issue is sparse, I found a couple of examples how to achieve it with Spring, but nothing related to JavaEE.
https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-bootstrapping.html
https://beanvalidation.org/
https://beanvalidation.org/2.0/spec/#constraintdeclarationvalidationprocess-methodlevelconstraints-parameterconstraints
Note that declaring these constraints does not automatically cause their validation when the concerned methods are invoked. It’s the responsibility of an integration layer to trigger the validation of the constraints using a method interceptor, dynamic proxy or similar. See section Triggering method validation for more details.
https://beanvalidation.org/2.0/spec/#validationapi-triggeringmethodvalidation
Jakarta Bean Validation itself doesn’t trigger the evaluation of method constraints. That is, just annotating any methods or constructors with parameter or return value constraints doesn’t automatically enforce these constraints, just as annotating any fields or properties with bean constraints doesn’t enforce these either.
Update: It looks like the test mentioned above is working now, because we are manually throwing an exception for this. The issue is still valid though: there is currently no way to unit test whether validation constraints are in place (e.g. a Size annotation for the ISO code).