ConsumerAuthenticationFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String token = request.getHeader(HttpHeaders.AUTHORIZATION); Long consumerId = consumerAuthUtil.getConsumerId(token); if (consumerId == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } consumerAuthUtil.storeConsumerId(request, consumerId); consumerAuditUtil.audit(request, consumerId); chain.doFilter(req, resp); } ConsumerAuthenticationFilter(ConsumerAuthUtil consumerAuthUtil, ConsumerAuditUtil consumerAuditUtil); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain); @Override void destroy();  }
@Test public void testAuthSuccessfully() throws Exception { String someToken = "someToken"; Long someConsumerId = 1L; when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken); when(consumerAuthUtil.getConsumerId(someToken)).thenReturn(someConsumerId); authenticationFilter.doFilter(request, response, filterChain); verify(consumerAuthUtil, times(1)).storeConsumerId(request, someConsumerId); verify(consumerAuditUtil, times(1)).audit(request, someConsumerId); verify(filterChain, times(1)).doFilter(request, response); }
@Test public void testAuthFailed() throws Exception { String someInvalidToken = "someInvalidToken"; when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someInvalidToken); when(consumerAuthUtil.getConsumerId(someInvalidToken)).thenReturn(null); authenticationFilter.doFilter(request, response, filterChain); verify(response, times(1)).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), anyString()); verify(consumerAuthUtil, never()).storeConsumerId(eq(request), anyLong()); verify(consumerAuditUtil, never()).audit(eq(request), anyLong()); verify(filterChain, never()).doFilter(request, response); }