### Question:
EmailValidator extends BeanValidator { @Override public void validate(ValidationContext validationContext) { String email = (String) validationContext.getProperty().getValue(); PoulpeUser user = (PoulpeUser) validationContext.getBindContext().getValidatorArg("user"); boolean beanValidationFailed = beanValidationFails(validationContext, new PoulpeUser(user.getUsername(), email, "", "")); if (!beanValidationFailed) { checkForUniqueness(validationContext, email, user); } } EmailValidator(UserService userService); @Override void validate(ValidationContext validationContext);  }### Answer:
@Test public void tooLongMailShouldFailValidation() { givenBindContextReturnsMailAndUserId(RandomStringUtils.randomAlphanumeric(255) + "@rambler.ru", 1); validator.validate(context); verify(context).setInvalid(); }
@Test public void tooLongMailDomainShouldNotFailValidation(){ givenBindContextReturnsMailAndUserId("less.luter@email.PHOTOGRAPHY", 1 ); validator.validate(context); verify(context,never()).setInvalid(); }
@Test public void wrongEmailPatternShouldFailValidation() { givenBindContextReturnsMailAndUserId("asdasd", 1); validator.validate(context); verify(context).setInvalid(); }
@Test public void blankEmailPatternShouldFailValidation() { givenBindContextReturnsMailAndUserId("", 1); validator.validate(context); verify(context).setInvalid(); }
@Test public void validEmailShouldPassValidation() { givenBindContextReturnsMailAndUserId("some_email@somedomain.com", 1); validator.validate(context); verify(context, never()).setInvalid(); }
@Test public void duplicatedMailShouldFailValidation() throws Exception { PoulpeUser user1 = PoulpeUser.withId(1); PoulpeUser user2 = PoulpeUser.withId(2); user1.setEmail("user1@jtalks.org"); user2.setEmail("somebody@mail.ru"); givenBindContextReturnsMailAndUserId(user1.getEmail(), user2.getId()); storeUsersInMockedDb(user1, user2); validator.validate(context); verify(context).setInvalid(); }
@Test public void testTheSameEmailValidation() throws Exception { PoulpeUser user = TestFixtures.user(); givenBindContextReturnsMailAndUserId(user.getEmail(), user.getId()); storeUsersInMockedDb(user); validator.validate(context); verify(context, never()).setInvalid(); }
@Test public void testTwoUniqueEmails() throws Exception { PoulpeUser user1 = PoulpeUser.withId(1); PoulpeUser user2 = PoulpeUser.withId(2); user1.setEmail("user1@jtalks.org"); user2.setEmail("user2@mail.ru"); givenBindContextReturnsMailAndUserId("user3@mail.ru", user2.getId()); storeUsersInMockedDb(user1, user2); validator.validate(context); verify(context, never()).setInvalid(); }