I was trying to follow the instructions in the article below trying to implement a simple annotation just to test if a string was a certain length as a test. My goal was to have this annotation thrown an exception at runtime if the String doesn't meet certain conditions.
https://dzone.com/articles/create-your-own-constraint-with-bean-validation-20
I'm able to add the annotation to the code and everything compiles & builds fine. However, no matter what I do when I try to invoke it from a unit test I cannot get the validation to run. I feel like I'm missing something obvious but I do not know what it is. Note that this is a Java SE backend service so no UI component. Let's take an example (which I know already exists of checking if a String is null or empty)
Here is the interface:
@Documented
@Constraint(validatedBy = {NotEmptyValidator.class})
@Target({METHOD, FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface NotEmpty {
Class<?>[] groups() default {};
String message() default "test message";
Class<? extends Payload>[] payload() default {};
}
Here is the validator:
public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String> {
@Override
public void initialize(final NotEmpty notEmpty) {
}
@Override
public boolean isValid(String notEmptyField, ConstraintValidatorContext constraintValidatorContext) {
return !Strings.isNullOrEmpty(notEmptyField);
}
}
Note that retention is set to RUNTIME but it doesn't actually validate when I run a unit test on a String parameter that is an empty string.. how do I actually turn this validation on and get it to run?
for example if i have a random utility method
public static String testAnnotation(@NotEmpty final String foo) {
return foo + "bar"
}
If I call that from a unit test even if the string is null or empty the validation doesn't run. Any help would be appreciated!