Mr.Qbs Mr.Qbs - 1 month ago 6x
Java Question

How to run one concrete validation using Javax Constraint Validator

My goal: Run ONLY ValidatorOne in tests.

Validated class:

public class MyClass{...}

Main Validator (Agregation annotation):

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

ValidatorOne Test:

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

public void validate_with_validatorOne() {
MyClass myClass = new 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?


I ended with simple validation test that looks like this:

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


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

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