### Question:
ChangedEmailValidator implements ConstraintValidator<ChangedEmail, UserProfileDto> { @Override public boolean isValid(UserProfileDto userProfile, ConstraintValidatorContext context) { String changedEmail = userProfile.getEmail(); if (changedEmail == null) { return true; } String currentUserEmail = getEmailOfUser(userProfile.getUserId()); if (ObjectUtils.equals(changedEmail, currentUserEmail)) { return true; } else { boolean userWithTheSameChangedEmailExists = userDao.getByEmail(changedEmail) != null; if(userWithTheSameChangedEmailExists){ context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(message) .addNode("email") .addConstraintViolation(); } return !userWithTheSameChangedEmailExists; } } @Autowired  ChangedEmailValidator(UserService userService, UserDao userDao); @Override void initialize(ChangedEmail constraintAnnotation); @Override boolean isValid(UserProfileDto userProfile, ConstraintValidatorContext context);  }### Answer:
@Test public void emptyEmailShouldBeValidBecauseItIsNotBusy() { UserProfileDto editedUserProfile = new UserProfileDto(); editedUserProfile.setEmail(null); boolean isValid = validator.isValid(editedUserProfile, validatorContext); assertTrue(isValid, "Empty email should be valid, becuase it isn't busy."); }
@Test public void notChangedEmailShouldBeValid() { UserProfileDto editedUserProfile = new UserProfileDto(); editedUserProfile.setEmail(userEmail); boolean isValid = validator.isValid(editedUserProfile, validatorContext); assertTrue(isValid, "Email of current user isn't valid."); }
@Test public void changedEmailShouldBeValidIfItIsNotBusy() { UserProfileDto editedUserProfile = new UserProfileDto(); editedUserProfile.setEmail("new_current_user@gmail.com"); boolean isValid = validator.isValid(editedUserProfile, validatorContext); assertTrue(isValid, "New email isn't taken, so it must be valid."); }
@Test public void changedEmailShouldNotBeValidIfItIsBusy() { when(userDao.getByEmail(anyString())).thenReturn( new JCUser("new_current_user@gmail.com", "email", "password")); UserProfileDto editedUserProfile = new UserProfileDto(); editedUserProfile.setEmail("new_current_user@gmail.com"); when(validatorContext.buildConstraintViolationWithTemplate(null)). thenReturn(violationBuilder); when(violationBuilder.addNode(anyString())). thenReturn(nodeBuilderDefinedContext); boolean isValid = validator.isValid(editedUserProfile, validatorContext); assertFalse(isValid, "New email is taken, so it must be invalid."); }