### Question:
UserInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { checkToken(request.getHeader(X_CLIENT_TOKEN)); String userInfoString = StringUtils.defaultIfBlank(request.getHeader(X_CLIENT_TOKEN_USER), "{}"); UserContextHolder.getInstance().setContext(new ObjectMapper().readValue(userInfoString, Map.class)); return true; }  @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler); @Override void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex); static final String X_CLIENT_TOKEN_USER; static final String X_CLIENT_TOKEN; }### Answer:
@Test public void preHandle_当未设置token_user_那么正常处理下一个handle() throws Exception { UserInterceptor userInterceptor = new UserInterceptor(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); userInterceptor.preHandle(request, response, new Object()); }
@Test public void preHandle_当设置token的username_那么username可以在线程中拿出来用() throws Exception { UserInterceptor userInterceptor = new UserInterceptor(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("x-client-token-user", "{\"user_name\":\"zhangsan\"}"); MockHttpServletResponse response = new MockHttpServletResponse(); userInterceptor.preHandle(request, response, new Object()); Assert.assertEquals(UserContextHolder.getInstance().getUsername(), "zhangsan"); }