MongoUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repository.findById(username).orElseThrow(()->new UsernameNotFoundException(username)); }  @Override UserDetails loadUserByUsername(String username);  }
@Test public void shouldLoadByUsernameWhenUserExists() { final User user = new User(); when(repository.findById(any())).thenReturn(Optional.of(user)); UserDetails loaded = service.loadUserByUsername("name"); assertEquals(user, loaded); }
@Test(expected = UsernameNotFoundException.class) public void shouldFailToLoadByUsernameWhenUserNotExists() { service.loadUserByUsername("name"); }