0

Imagine a case we have such dto

@CheckUserDetailsNotNull
@CheckUserMobileValid
@CheckUserEmailValid
public class UserDto {}

and, ofcourse, for each of these annotations there are dedicated constraint validators, for example for @CheckUserMobileValid there is UserMobileValidator

So, I'm gonna write a unit test for the UserMobileValidator but in scope of the test I wanna check only @CheckUserMobileValid without trigger the other validators. Here is the simple test:

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());
}

It works just fine but the all validators will be triggered, Is there a way to trigger only UserMobileValidator?

Tymur Berezhnoi
  • 706
  • 1
  • 14
  • 27
  • 1
    If you just want to test the validator class, then why are you setting up a whole validation context? Simply instantiate the validator and test it. With the above test, you are testing whether the validation framework does its job (which should be tested by the framework's owner). – Seelenvirtuose Aug 01 '18 at 08:37
  • @Seelenvirtuose Yes, it sounds reasonable, I just wanted to know if there is way to ignore the other constraints. Thanks – Tymur Berezhnoi Aug 01 '18 at 08:40
  • Well ... You could go with validation groups, but that would be a bit tricky for that case. – Seelenvirtuose Aug 01 '18 at 08:42

0 Answers0