如何仅针对特定约束验证DTO而忽略其他约束?

时间:2018-08-01 07:47:17

标签: java bean-validation hibernate-validator

想像一下我们有这样的dto

@CheckUserDetailsNotNull
@CheckUserMobileValid
@CheckUserEmailValid
public class UserDto {}

,当然,对于每个注释,都有专用的约束验证器,例如,对于 @CheckUserMobileValid ,有 UserMobileValidator

因此,我要为 UserMobileValidator 编写单元测试,但是在测试范围内,我只想检查 @CheckUserMobileValid 而不会触发其他验证程序。这是简单的测试:

public class UserMobileValidatorTest {

private Validator validator;

@Before
public void setup() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void mobileShouldBeValid() {
    UserDto userDto = new UserDto();
    userDto.setMobile("062233442234");
    Set<ConstraintViolation<UserDto>> constraintViolations = validator.validate(UserDto);
    Assert.assertEquals("Expected validation error not found", 1, constraintViolations.size());
}

它工作得很好,但是所有验证器都会被触发,有没有办法只触发 UserMobileValidator

0 个答案:

没有答案