LdapUserService implements UserService { @Override public String retrieve(Properties properties) throws UserException { User user = new User(); String userName = properties.getProperty("userName"); String key; Attribute value; SearchControls searchControls = getSearchControls(this.userAttributes); ctx = getContext(); try { NamingEnumeration<SearchResult> answer = ctx.search(this.ldapSearchBase, this.ldapFilterAttribute + "=" + userName, searchControls); if (answer.hasMore()) { Attributes attrs = answer.next().getAttributes(); NamingEnumeration<String> attrsKeys = attrs.getIDs(); while (attrsKeys.hasMoreElements()) { key = attrsKeys.next(); value = attrs.get(key); if (this.keyMap.containsKey(key)) { user.setUserInformation(this.keyMap.get(key), value.toString()); } else { user.setUserInformation(key, value.toString()); } } } else { throw new UserException("User not found: " + userName + ". "); } } catch (NamingException | NullPointerException ex) { throw new UserException("Could not make connection to LDAP Server. User not found: " + userName + ". "); } this.users.put(userName, user); return userName; } LdapUserService(Config config);  LdapUserService(DirContext context, String[] userAttributes); @Override String create(User user); @Override void delete(String userName); @Override User getUser(String userName); @Override String retrieve(Properties properties); @Override void update(String userName, User user);  }
@Test(expected = UserException.class) public void testBadUsername() throws NamingException, UserException { String userName = "testUsername"; Properties props = new Properties(); props.setProperty("userName", userName); DirContext ctx = mock(InitialDirContext.class); String[] userAttributes = mockUserAttributes(); LdapUserService lus = new LdapUserService(ctx, userAttributes); NamingEnumeration<SearchResult> mockSearchResults = mock(NamingEnumeration.class); when(ctx.search(any(String.class), any(String.class), any(SearchControls.class))) .thenReturn(mockSearchResults); lus.retrieve(props); }
@Test(expected = UserException.class) public void testBadConnection() throws UserException, NamingException { String userName = "testUsername"; Properties props = new Properties(); props.setProperty("userName", userName); DirContext ctx = mock(InitialDirContext.class); String[] userAttributes = mockUserAttributes(); LdapUserService lus = new LdapUserService(ctx, userAttributes); lus.retrieve(props); }