UserContext { public User getCurrentUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { throw new AuthenticationCredentialsNotFoundException("No authentication"); } Object obj = auth.getPrincipal(); if (!(obj instanceof SecuredUser)) { throw new AuthenticationCredentialsNotFoundException("Invalid authentication with " + obj); } SecuredUser securedUser = (SecuredUser) obj; return securedUser.getUser(); }  User getCurrentUser();  }
@Test public void testGetUser() { UserContext userCtx = new UserContext(); try { userCtx.getCurrentUser(); assertTrue(false); } catch (AuthenticationCredentialsNotFoundException e) { assertTrue(true); } UserDetails user = userDetailService.loadUserByUsername(getTestUser().getUserId()); Authentication oriAuth = SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "123"); SecurityContextHolder.getContext().setAuthentication(token); userCtx.getCurrentUser(); assertTrue(true); SecurityContextHolder.getContext().setAuthentication(oriAuth); }