### Question:
UserValidator implements Validator { public boolean isUserNameValid(String username) { String expression = "^[\\w][\\Q_\\E\\w-\\.]{1,49}$"; if (StringUtils.isEmpty(username)) { return true; } try { Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(username); return matcher.matches(); } catch (PatternSyntaxException pex) { log.error("Username Pattern Syntax exception in UserValidator", pex); return false; } }  @Override boolean supports(Class<?> clazz); @Override void validate(Object obj, Errors errors); boolean isUserNameValid(String username); boolean isUserNameAsEmailValid(String username);  }### Answer:
@Test public void isUserNameValid_shouldValidateUsernameWithOnlyAlphaNumerics() { Assert.assertTrue(validator.isUserNameValid("AB")); }
@Test public void isUserNameValid_shouldValidateUsernameWithAlphaDashAndUnderscore() { Assert.assertTrue(validator.isUserNameValid("A-_.")); }
@Test public void isUserNameValid_shouldValidateUsernameWithAlphaDashUnderscoreAndDot() { Assert.assertTrue(validator.isUserNameValid("A-_.B")); }
@Test public void isUserNameValid_shouldValidateUsernameWithExactlyMaxSizeName() { String username = "12345678901234567890123456789012345678901234567890"; Assert.assertEquals(50, username.length()); Assert.assertTrue(validator.isUserNameValid(username)); }
@Test public void isUserNameValid_shouldNotValidateUsernameWithLessThanMinimumLength() { Assert.assertFalse(validator.isUserNameValid("A")); }
@Test public void isUserNameValid_shouldNotValidateUsernameWithInvalidCharacter() { Assert.assertFalse(validator.isUserNameValid("A*")); }
@Test public void isUserNameValid_shouldNotValidateUsernameWithMoreThanMaximumSize() { String username = "12345678901234567890123456789012345678901AAAAABBBAABABABABA"; Assert.assertTrue(username.length() > 50); Assert.assertFalse(validator.isUserNameValid(username)); }
@Test public void isUserNameValid_shouldValidateWhenUsernameIsNull() { Assert.assertTrue(validator.isUserNameValid(null)); }
@Test public void isUserNameValid_shouldValidateWhenUsernameIsTheEmptyString() { Assert.assertTrue(validator.isUserNameValid("")); }
@Test public void isUserNameValid_shouldNotValidateWhenUsernameIsWhitespaceOnly() { Assert.assertFalse(validator.isUserNameValid(" ")); }