I have below property in POJO -
@NotNull(message = "dateOfBirth is required")
@DateFormat(format = "YYYY-MM-DD", message = "dateOfBirth should be in format YYYY-MM-DD")
@JsonDeserialize(using = LocalDateDeserializer.class)
LocalDate dateOfBirth;
For custom message of validation I have added below validator -
@Documented
@Constraint(validatedBy = DateFormatValidator.class)
@Target( { METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface DateFormat {
String format();
String message() default "Invalid date format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class DateFormatValidator implements ConstraintValidator<DateFormat, LocalDate> {
private String dateFormat;
@Override
public void initialize(DateFormat constraintAnnotation){
this.dateFormat = constraintAnnotation.format();
}
@Override
public boolean isValid(LocalDate value, ConstraintValidatorContext context) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try{
sdf.setLenient(false);
Date d = sdf.parse(String.valueOf(value));
return true;
}catch(ParseException e) {
return false;
}
}
}
Now for my junit I am adding -
.dateOfBirth(LocalDate.of(1984, 03, 12))
but when I run my junit, I am getting my validator message means dateOfBirth should be in format YYYY-MM-DD. How can I pass date into my junit to satisfy above condition and should run junit.