AccountUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Users user = usersRepository.loadUserByUsername(username); if (user == null) { throw new UsernameNotFoundException("Invalid username/password"); } if (user.getFailedLoginAttempts() >= maxFailedAttempts) { Calendar cal = Calendar.getInstance(); if (user.getLockoutTime() != null) if (cal.getTimeInMillis() - user.getLockoutTime().getTimeInMillis() >= autoUnlockInterval) { user.setAccountNonLocked(true); user.setLockoutTime(null); user.setFailedLoginAttemptsToZero(); usersRepository.updateUser(user); return user; } user.setAccountNonLocked(false); } return user; } AccountUserDetailsService(short maxFailedAttempts,
			long autoUnlockInterval, UsersRepository usersRepository); @Override UserDetails loadUserByUsername(String username);  }
@Test public void testLoadUserByUsername_when_succeeds() { Users user = mock(Users.class); when(usersRepository.loadUserByUsername(username)).thenReturn(user); when(user.getFailedLoginAttempts()).thenReturn(0); when(user.getLockoutTime()).thenReturn(null); assertEquals(accountUserDetailsService.loadUserByUsername(username), user); }
@Test(expected = UsernameNotFoundException.class) public void testLoadUserByUsername_when_username_is_wrong_verify_that_UsernameNotFoundException_is_thrown() { when(usersRepository.loadUserByUsername(username)).thenReturn(null); accountUserDetailsService.loadUserByUsername(username); }
@Test() public void testLoadUserByUsername_when_account_is_lockout_verify_that_lockout_flag_is_set() { Users user = mock(Users.class); when(usersRepository.loadUserByUsername(username)).thenReturn(user); when(user.getFailedLoginAttempts()).thenReturn(5); when(user.getLockoutTime()).thenReturn(Calendar.getInstance()); assertEquals(accountUserDetailsService.loadUserByUsername(username), user); verify(user).setAccountNonLocked(false); }
@Test() public void testLoadUserByUsername_when_account_is_lockout_verify_that_account_is_unlocked_after_5_minutes() { Users user = mock(Users.class); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Calendar.getInstance().getTimeInMillis() - 300000); when(usersRepository.loadUserByUsername(username)).thenReturn(user); when(user.getFailedLoginAttempts()).thenReturn(5); when(user.getLockoutTime()).thenReturn(cal); assertEquals(accountUserDetailsService.loadUserByUsername(username), user); verify(user).setLockoutTime(null); verify(user).setFailedLoginAttemptsToZero(); verify(user).setAccountNonLocked(true); verify(usersRepository).updateUser(any(Users.class)); }