Search code examples
javaservlet-filtersrest-assured

Can I test servlet filters with REST Assured?


I have a Spring Boot MVC app with a @WebFilter that adds a custom header to every response. It works fine when I actually run the app, but I'm a little surprised that the filter doesn't run during my REST Assured test.

There's nothing fancy in my test; it basically reduces to

RestAssuredMockMvc.standaloneSetup(new MyController());
boolean headerExists = given().when().get().headers().hasHeaderWithName("my-header");

Is this expected? Should I be doing something extra to set up the filter chain?


Solution

  • MockMvc is an infrastructure to test your controllers and not the full web container.

    If you want to have the filters working you have to add it. This would look something like:

    @Autowired
    private WebApplicationContext wac;
    
    private MockMvc mockMvc;
    
    @Before
    public void setUp() {
       Collection<Filter> filterCollection = wac.getBeansOfType(Filter.class).values();
       Filter[] filters = filterCollection.toArray(new Filter[filterCollection.size()]);
       mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(filters).build();
    }