mercredi 11 avril 2018

Java Spring Boot - How to test ConstraintValidator?

I have no idea how to test isValid method because format field will take value from model annotated field

@DateFormatConstraint(value="yyyy-MM-dd HH:mm:ss")
private String time;

This @DateFormatConstraint is interface which only have // @return value String value();

public class DateFormatValidator implements ConstraintValidator {

private String format;

@Override
public void initialize(DateFormatConstraint constraintAnnotation) {
    format = constraintAnnotation.value();
}

@Override
public boolean isValid(String date) {

    if ( date == null ) {
        return true;
    }

    DateFormat dateFormat = new SimpleDateFormat( format );
    dateFormat.setLenient( false );
    try {
        dateFormat.parse(date);
        return true;
    } 
    catch (ParseException e) {
        return false;
    }
}

}

********************TEST*****************

Maybe l need to @Bean that class with some trick in Spring Boot to get value from that field? Thanks

public class DateFormatValidatorTest {

DateFormatValidator validator;

String dateFormat;

@Test
public void succesfullDateValidator() {

    boolean validate = validator.isValid(dateFormat);

    assertTrue(validate);
}

}

Aucun commentaire:

Enregistrer un commentaire