UserIdMDCPutFilter extends AbstractMDCPutFilter { @Override protected String getMDCValue(HttpServletRequest request, HttpServletResponse response) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } return principal.toString(); } return null; }  void setAttributeName(String attibuteName);  }
@Test public void testGetMDCValue() { UserIdMDCPutFilter mdcPutFilter = new UserIdMDCPutFilter(); String userName = "terasoluna@nttd.co.jp"; securityContext = mock(SecurityContext.class); authentication = mock(Authentication.class); user = new User(userName, "yyyy", Arrays.asList( new SimpleGrantedAuthority("user"))); when(authentication.getPrincipal()).thenReturn(user); when(securityContext.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(securityContext); String mdcValueStr = mdcPutFilter.getMDCValue(request, response); assertThat(mdcValueStr, is(userName)); }
@Test public void testGetMDCValueNullAuthentication() { UserIdMDCPutFilter mdcPutFilter = new UserIdMDCPutFilter(); String mdcValueStr = mdcPutFilter.getMDCValue(request, response); assertThat(mdcValueStr, is(nullValue())); }
@Test public void testGetMDCValuePrincipalStringValue() { UserIdMDCPutFilter mdcPutFilter = new UserIdMDCPutFilter(); String userName = "terasoluna@nttd.co.jp"; securityContext = mock(SecurityContext.class); authentication = mock(Authentication.class); when(authentication.getPrincipal()).thenReturn(userName); when(securityContext.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(securityContext); String mdcValueStr = mdcPutFilter.getMDCValue(request, response); assertThat(mdcValueStr, is(userName)); }