### Question:
CustomUserService extends DefaultUserService { @Override public User getAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof User) { return (User) authentication.getPrincipal(); } else { throw new SecurityException("Could not get the authenticated user!"); } } @Autowired  CustomUserService(UserRepository userRepository,
                             PageRepository pageRepository,
                             WidgetRepository widgetRepository,
                             PageTemplateRepository pageTemplateRepository,
                             CategoryRepository categoryRepository,
                             PersonRepository personRepository); @Override UserDetails loadUserByUsername(String username); @Override User getAuthenticatedUser();  }### Answer:
@Test public void testGetAuthenticatedUser() throws Exception { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER")); UserDetails userDetails = new UserImpl("1", "canonical"); Authentication authentication = new TestingAuthenticationToken(userDetails, "canonical", grantedAuthorities); SecurityContextHolder.getContext().setAuthentication(authentication); User returnedUser = userService.getAuthenticatedUser(); assertEquals(returnedUser, userDetails); }
@Test(expected = SecurityException.class) public void testGetAuthenticatedUser_fail() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); userService.getAuthenticatedUser(); assertFalse("Method should throw Exception", true); }