In Spring Boot 2.6, we've introduced a new filter that's only registered for ERROR dispatches. This works fine at runtime and in integration tests over HTTP, but doesn't work as intended when testing with MockMvc. I overlooked the fact that MockMvc's filter chain includes every known filter, irrespective of the request's dispatcher type. When adding a filter, it would be useful to be able to specify the filter's dispatcher types, as you can do with the Servlet API. In the meantime, we can fix Boot by updating the filter to ignore non-ERROR requests.

Comment From: rstoyanchev

On AbstractMockMvcBuilder we have:

  • addFilters(Filter... filters)
  • addFilter(Filter filter, String... urlPatterns)

We could also have:

  • addFilter(Filter filter, DispatcherType dispatcherType, String... urlPatterns)

Is this what you had in mind as well?

Comment From: wilkinsona

To align with the Servlet API on FilterRegistration, I think EnumSet<DispatcherType> would be better than DispatcherType.

Comment From: viktorardelean

@wilkinsona I would like to implement this enhancement.

From what I understood, I need to add addFilter(Filter filter, DispatcherType dispatcherType, String... urlPatterns) to AbstractMockMvcBuilder and also declare it in the ConfigurableMockMvcBuilder interface.

Inside the new addFilter, I will check if there is any DispatcherType.ERROR in the set. If there is, I will not add the filter to the filterslist.

Here is how it will look like:

@Override
public final  <T extends B> T addFilter(Filter filter, EnumSet<DispatcherType> dispatcherType, String... urlPatterns { 
    Assert.notNull(filter, "filter cannot be null");
    Assert.notNull(urlPatterns, "urlPatterns cannot be null");
    Assert.notNull(dispatcherType, "dispatcherType cannot be null");
    if (dispatcherType.contains(DispatcherType.ERROR)) {
        return self();
    }
    if (urlPatterns.length > 0) {
        filter = new PatternMappingFilterProxy(filter, urlPatterns);
    }
    this.filters.add(filter);
    return self();
}

Comment From: wilkinsona

Thanks, but I am not a member of the Spring Framework team. If you are interested in contributing, @rstoyanchev would be a better person to discuss things with.

Comment From: viktorardelean

@rstoyanchev Could you kindly give your feedback on my comment? Then I can implement it and raise a PR. Thanks!

Comment From: viktorardelean

@rstoyanchev Could you please give an update on this? I want to make sure that my approach on this is correct. Thanks!