【发布时间】:2019-08-06 06:21:30
【问题描述】:
我在 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;
对于验证的自定义消息,我在验证器下方添加了 -
@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;
}
}
}
现在我要为我的 junit 添加 -
.dateOfBirth(LocalDate.of(1984, 03, 12))
但是当我运行我的 junit 时,我收到了验证器消息,这意味着 dateOfBirth 的格式应该是 YYYY-MM-DD。如何将日期传递到我的 junit 以满足上述条件并且应该运行 junit。
【问题讨论】:
标签: java-8