### Question:
CollectUserAgentFilter implements Filter { @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { try { final HttpServletRequest request = (HttpServletRequest) servletRequest; String ua = request.getHeader( "User-Agent" ); if ( ua != null && !ua.isEmpty() ) { output.add( ua.split( " " )[0] ); } } catch ( RuntimeException e ) { } filterChain.doFilter( servletRequest, servletResponse ); } CollectUserAgentFilter( RecentK<String> output ); @Override void init( FilterConfig filterConfig ); @Override void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ); @Override void destroy();  }### Answer:
@Test public void shouldRecordASingleUserAgent() throws IOException, ServletException { filter.doFilter( request( "the-agent" ), null, filterChain ); assertThat( agents.recentItems(), hasItem( "the-agent" ) ); }
@Test public void shouldOnlyRecordTheFirstFieldOfTheUserAgentString() throws IOException, ServletException { filter.doFilter( request( "the-agent other-info" ), null, filterChain ); assertThat( agents.recentItems(), hasItem( "the-agent" ) ); }
@Test public void shouldRecordMultipleUserAgents() throws IOException, ServletException { filter.doFilter( request( "agent1" ), null, filterChain ); filter.doFilter( request( "agent2" ), null, filterChain ); assertThat( agents.recentItems(), hasItems( "agent1", "agent2" ) ); }
@Test public void shouldNotReportDuplicates() throws IOException, ServletException { filter.doFilter( request( "the-agent" ), null, filterChain ); filter.doFilter( request( "the-agent" ), null, filterChain ); assertThat( agents.recentItems(), hasSize( 1 ) ); }
@Test public void shouldCopeIfThereIsNoUserAgentHeader() throws IOException, ServletException { filter.doFilter( request( null ), null, filterChain ); assertThat( agents.recentItems(), hasSize( 0 ) ); }
@Test public void shouldSwallowAnyExceptionsThrownByTheRequest() throws IOException, ServletException { HttpServletRequest request = mock( HttpServletRequest.class ); when(request.getHeader( anyString() )).thenThrow( new RuntimeException() ); filter.doFilter( request, null, filterChain ); }
@Test public void shouldReturnTheRequest() throws IOException, ServletException { ServletRequest original = request( "the-agent" ); filter.doFilter( original, null, filterChain ); verify(filterChain).doFilter( original, null ); }