自定义验证未在java中使用的注释

时间:2015-02-13 12:27:40

标签: java hibernate annotations

我已经创建了自定义注释:

@Constraint(validatedBy = BeginsWithACapitalLetterValidator.class)
@Target({ FIELD, METHOD, ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface BeginsWithACapitalLetter {
    String message() default "{Should begin with a capital!}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

通过以下方式验证:

public class BeginsWithACapitalLetterValidator implements ConstraintValidator<BeginsWithACapitalLetter, String> {

    @Override
    public void initialize(BeginsWithACapitalLetter constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        String valueAsString = (String) value;
        System.out.println(valueAsString);
        if (valueAsString.length() > 0) {
            return Character.isUpperCase(valueAsString.charAt(0));
        }

        return false;
    }
}

我将其应用于单个字段:

public class Person {

    @BeginsWithACapitalLetter
    private String forename;

    public String getForename() {
        return forename;
    }

    public void setForename(String forename) {
        this.forename = forename;
    }
}

我希望用以下方法测试:

    @Test
    public void nameShouldFailValidationIfFirstLetterNotCapital() {
        // Given
        Person person = new Person();
        person.setForename("name");

        // When
        Set<ConstraintViolation<Object>> violations = validate(person.getForename());

        // Then
        assertEquals(1, violations.size());
    }

    private Set<ConstraintViolation<Object>> validate(Object obj) {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator.validate(obj);
    }

但测试失败且没有违规行为:

  

java.lang.AssertionError:expected:&lt; 1&gt;但是:&lt; 0&gt;

我错过了什么?


使用的进口商品:

'javax:javaee-api:7.0'
'org.hibernate:hibernate-validator:5.1.3.Final'

1 个答案:

答案 0 :(得分:1)

您必须验证不是名字的人。而不是

Set<ConstraintViolation<Object>> violations = validate(person.getForename());

使用

Set<ConstraintViolation<Object>> violations = validate(person);