Mr.Qbs Mr.Qbs - 2 months ago 15
Java Question

How to run one concrete validation using Javax Constraint Validator

My goal: Run ONLY ValidatorOne in tests.

Validated class:

@ValidMyClass
public class MyClass{...}


Main Validator (Agregation annotation):

@TypeValidation
@ValidatorOne
@ValidatorTwo
@Constraint(validatedBy = {})
public @interface ValidMyClass {...}


ValidatorOne Test:

private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

@Test
public void validate_with_validatorOne() {
MyClass myClass = new MyClass();

assertIsValid(myClass);
}

private void assertIsValid(Object o) {
Set<ConstraintViolation<Object>> violations = validator.validate(o, Default.class);
assertThat(violations, is(empty()));
}





When I run test it runs both validators.

I tried to use "groups" annotation property but it's not working for agregated validators.

Note: I dont want to use two validator annotations on MyClass - it looks not so clean as agregation annotation ValidMyClass.

Do you know anu solution of my problem?

Answer

I ended with simple validation test that looks like this:

@Test
public void simpleTest(){
    ValidatorOneValidator validator = new ValidatorOneValidator(); //Class response for validation in ValidatorOne
    MyClass myClass = givenAValidMyClass(); //Some fixture

    validator.initialize(myClass.getClass().getAnnotation(ValidMyClass.class).annotationType().getAnnotation(ValidatorOne.class));

    assertTrue(validator.isValid(myClass, null));
}

This is how I test only one validator without calling all other validators attached to MyClass.