### Question:
TraceeFilter implements Filter { @Override public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) { doFilterHttp((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain); } else { filterChain.doFilter(servletRequest, servletResponse); } } TraceeFilter();   TraceeFilter(TraceeBackend backend, HttpHeaderTransport transportSerialization); @Override final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain); @Override final void init(final FilterConfig filterConfig); @Override final void destroy(); static final String PROFILE_INIT_PARAM; }### Answer:
@Test public void testWriteResponseHeaderEvenIfFilterChainThrowsAnException() throws Exception { backend.put("foobi", "yes sir"); doThrow(new RuntimeException("Bad is bad")).when(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); try { unit.doFilter(httpServletRequest, httpServletResponse, filterChain); fail("Expected RuntimeException"); } catch (RuntimeException ignored) { } verify(httpServletResponse, atLeastOnce()).setHeader(eq(TraceeConstants.TPIC_HEADER), contains("foobi=yes+sir")); }
@Test public void testDoesNotCreateAResponseHeaderWhenBackendIsEmpty() throws Exception { doThrow(new RuntimeException("Bad is bad")).when(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); try { unit.doFilter(httpServletRequest, httpServletResponse, filterChain); fail("Expected RuntimeException"); } catch (RuntimeException ignored) { } verify(httpServletResponse, never()).setHeader(anyString(), anyString()); }
@Test public void shouldDelegateToNextInFilterChainForNonHttpRequests() throws Exception { ServletRequest servletRequest = mock(ServletRequest.class); ServletResponse servletResponse = mock(ServletResponse.class); unit.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); }
@Test public void shouldDelegateToNextInFilterChainForHttpRequests() throws Exception { unit.doFilter(httpServletRequest, httpServletResponse, filterChain); verify(filterChain).doFilter(httpServletRequest, httpServletResponse); }