title: Spring: How to test a filter which requires Spring Security
body: <p>I've written a filter which operates on the Principal of a HTTP request.  So in my application I've made sure that it runs after the Spring Security filters.  It works fine.</p>
  
  <p>However, I'm having trouble testing it.  I read <a href="https://spring.io/blog/2014/05/23/preview-spring-security-test-web-security" rel="nofollow noreferrer">this</a> and followed the steps to create this test:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration
  @WebAppConfiguration
  public class MyTest {
      @Autowired
      private WebApplicationContext context;
  
      @Autowired
      private Filter springSecurityFilterChain;
  
      private MockMvc mvc;
      @Before
      public void setup() {
          mvc = MockMvcBuilders
                  .webAppContextSetup(context)
                  .addFilters(springSecurityFilterChain, new MyFilter())
                  .build();
      }
  
      @Test
      public void anonymousCallsNotLogged() throws Exception {
          mvc.perform(post("/").with(anonymous()));
      }
  
      public static class MyFilter extends GenericFilterBean {
          @Override
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
              filterChain.doFilter(servletRequest, servletResponse);
          }
      }
  
      @Configuration
      @EnableWebSecurity
      @EnableWebMvc
      static class Config extends WebSecurityConfigurerAdapter {
      }
  }
  </code></pre>
  
  <p>When I debug it, I do not see my filter fire, but I do see the Spring Security filters working.</p>
  
  <p>However when I switch their order:</p>
  
  <pre><code>.addFilters(new MyFilter(), springSecurityFilterChain)
  </code></pre>
  
  <p>I see both fire.  Unfortunately in the wrong order!  It looks like the Spring Security stuff isn't call the rest of the filter chain.</p>
  
  <p>My question is - why is this happening and what can I do about it!?</p>