gpt4 book ai didi

java - java中未使用自定义验证注解

转载 作者:行者123 更新时间:2023-12-01 11:55:19 25 4
gpt4 key购买 nike

我创建了一个自定义注释:

@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: <1> but was: <0>

我错过了什么?

<小时/>

使用进口:

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

最佳答案

您必须验证此人而不是名字。所以而不是

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

使用

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

关于java - java中未使用自定义验证注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28499638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com