### Question:
RepositoryUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LOGGER.debug("Loading user by username: {}", username); User user = repository.findByEmail(username); LOGGER.debug("Found user: {}", user); if (user == null) { throw new UsernameNotFoundException("No user found with username: " + username); } ExampleUserDetails principal = ExampleUserDetails.getBuilder() .firstName(user.getFirstName()) .id(user.getId()) .lastName(user.getLastName()) .password(user.getPassword()) .role(user.getRole()) .socialSignInProvider(user.getSignInProvider()) .username(user.getEmail()) .build(); LOGGER.debug("Returning user details: {}", principal); return principal; } @Autowired  RepositoryUserDetailsService(UserRepository repository); @Override UserDetails loadUserByUsername(String username);  }### Answer:
@Test public void loadByUsername_UserNotFound_ShouldThrowException() { when(repositoryMock.findByEmail(EMAIL)).thenReturn(null); catchException(service).loadUserByUsername(EMAIL); Assertions.assertThat(caughtException()) .isExactlyInstanceOf(UsernameNotFoundException.class) .hasMessage("No user found with username: " + EMAIL) .hasNoCause(); verify(repositoryMock, times(1)).findByEmail(EMAIL); verifyNoMoreInteractions(repositoryMock); }
@Test public void loadByUsername_UserRegisteredByUsingFormRegistration_ShouldReturnCorrectUserDetails() { User found = new UserBuilder() .email(EMAIL) .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .password(PASSWORD) .build(); when(repositoryMock.findByEmail(EMAIL)).thenReturn(found); UserDetails user = service.loadUserByUsername(EMAIL); ExampleUserDetails actual = (ExampleUserDetails) user; assertThat(actual) .hasFirstName(FIRST_NAME) .hasId(ID) .hasLastName(LAST_NAME) .hasPassword(PASSWORD) .hasUsername(EMAIL) .isActive() .isRegisteredUser() .isRegisteredByUsingFormRegistration(); verify(repositoryMock, times(1)).findByEmail(EMAIL); verifyNoMoreInteractions(repositoryMock); }
@Test public void loadByUsername_UserSignedInByUsingSocialSignInProvider_ShouldReturnCorrectUserDetails() { User found = new UserBuilder() .email(EMAIL) .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .signInProvider(SocialMediaService.TWITTER) .build(); when(repositoryMock.findByEmail(EMAIL)).thenReturn(found); UserDetails user = service.loadUserByUsername(EMAIL); ExampleUserDetails actual = (ExampleUserDetails) user; assertThat(actual) .hasFirstName(FIRST_NAME) .hasId(ID) .hasLastName(LAST_NAME) .hasUsername(EMAIL) .isActive() .isRegisteredUser() .isSignedInByUsingSocialSignInProvider(SocialMediaService.TWITTER); verify(repositoryMock, times(1)).findByEmail(EMAIL); verifyNoMoreInteractions(repositoryMock); }