Hibernate Validator method or constructor validation

后端 未结 2 1719
Happy的楠姐
Happy的楠姐 2021-01-15 09:16

How can I use Hibernate validator to validate the arguments inside the constructor or method? I want the validation to occur before the ValueObject creation so I can throw a

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-15 09:53

    You can do like this with hibernate validator using refection to validate the arguments:

    public class PersonTest {
    
    private static ExecutableValidator executableValidator;
    
    @BeforeClass
    public static void setUp() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        executableValidator = factory.getValidator().forExecutables();
    }
    @Test
    public void test() throws NoSuchMethodException {
        Constructor constructor = 
               Person.class.getConstructor(String.class, String.class, int.class);
    
        Set> violations = 
             executableValidator.validateConstructorParameters(constructor, new Object[]{null, "", 12});
             assertEquals(2, violations.size());
        }
    }
    

提交回复
热议问题