### Question:
UserProvider extends AbstractHttpContextInjectable<Principal> implements
  InjectableProvider<Context, Type> { @Override public Principal getValue(HttpContext httpContext) { Principal principal = httpContext.getRequest().getUserPrincipal(); if (principal == null) { final String user = httpContext.getRequest().getQueryParameters().getFirst(USER_NAME_PARAM); if (user != null) { principal = new Principal() { @Override public String getName() { return new UserParam(user).value(); } }; } } if (principal != null) { MDC.put("user", principal.getName()); } return principal; }  static void setUserPattern(String pattern); static Pattern getUserPattern(); @Override Principal getValue(HttpContext httpContext); @Override ComponentScope getScope(); @Override Injectable getInjectable(ComponentContext componentContext, Context context, Type type); static final String USER_NAME_PARAM; static final String USER_PATTERN_KEY; static final String USER_PATTERN_DEFAULT; }### Answer:
@Test @SuppressWarnings("unchecked") public void noUser() { MDC.remove("user"); HttpRequestContext request = Mockito.mock(HttpRequestContext.class); Mockito.when(request.getUserPrincipal()).thenReturn(null); MultivaluedMap map = Mockito.mock(MultivaluedMap.class); Mockito.when(map.getFirst(UserProvider.USER_NAME_PARAM)).thenReturn(null); Mockito.when(request.getQueryParameters()).thenReturn(map); HttpContext context = Mockito.mock(HttpContext.class); Mockito.when(context.getRequest()).thenReturn(request); UserProvider up = new UserProvider(); assertNull(up.getValue(context)); assertNull(MDC.get("user")); }
@Test @SuppressWarnings("unchecked") public void queryStringUser() { MDC.remove("user"); HttpRequestContext request = Mockito.mock(HttpRequestContext.class); Mockito.when(request.getUserPrincipal()).thenReturn(null); MultivaluedMap map = Mockito.mock(MultivaluedMap.class); Mockito.when(map.getFirst(UserProvider.USER_NAME_PARAM)).thenReturn("foo"); Mockito.when(request.getQueryParameters()).thenReturn(map); HttpContext context = Mockito.mock(HttpContext.class); Mockito.when(context.getRequest()).thenReturn(request); UserProvider up = new UserProvider(); assertEquals(up.getValue(context).getName(), "foo"); assertEquals(MDC.get("user"), "foo"); }
@Test @SuppressWarnings("unchecked") public void principalUser() { MDC.remove("user"); HttpRequestContext request = Mockito.mock(HttpRequestContext.class); Mockito.when(request.getUserPrincipal()).thenReturn(new Principal() { @Override public String getName() { return "bar"; } }); HttpContext context = Mockito.mock(HttpContext.class); Mockito.when(context.getRequest()).thenReturn(request); UserProvider up = new UserProvider(); assertEquals(up.getValue(context).getName(), "bar"); assertEquals(MDC.get("user"), "bar"); }