我正在尝试使用 javax.validation 验证一些 DTO,但似乎注释 @NotEmpty 不检查参数是否为 null。
这是我的课程:
人物类
public class Person {
@NotEmpty(message = "mandatoryParametersMissing")
private String name;
@NotNull(message = "mandatoryParametersMissing")
@Valid
private Job job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
@Override
public String toString() {
return "Person [name=" + name + ", job=" + job + "]";
}
}
工作类
public class Job {
@NotEmpty(message = "mandatoryParametersMissing")
private String name;
@NotNull(message = "mandatoryParametersMissing")
private Integer salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Job [name=" + name + ", salary=" + salary + "]";
}
}
当我尝试通过以下 JUnit 测试时,我失败了:
@Test(expected = BusinessServiceException.class)
public void testJobNameNull() {
Person samuel = new Person();
samuel.setName("Samuel Antequera");
Job programmer = new Job();
programmer.setSalary(18000);
samuel.setJob(programmer);
validatePerson(samuel);
}
这是验证 DTO 的方法:
public void validatePerson(Person in) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Person>> violations = validator.validate(in);
for (ConstraintViolation<Person> violation : violations) {
throw new BusinessServiceException(violation.getMessage(), violation.getPropertyPath().toString());
}
}
我的印象是 @NotEmpty 首先检查参数是否为 null,我错了吗?
三国纷争
慕沐林林
繁星点点滴滴
喵喔喔
德玛西亚99
相关分类