javaspring-mvcspring-testspring-test-mvcspring-mvc-test

Custom RequestMappingHandlerMapping with MockMvc


I have a custom RequestMappingHandlerMapping class that interprets a special annotation as part of its mapping criteria. It is being instantiated as a bean thusly:

@Configuration
@EnableWebMvc
public class ConfigServletConfig extends WebMvcConfigurerAdapter {
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new VersionRangeRequestMappingHandlerMapping();
        handlerMapping.setOrder(0);
        return handlerMapping;
    }
}

But when I create a MockMvc object for testing (with standaloneSetup) this mapping handler isn't being used. Without the extra annotation being taken into account, the mapping fails because I have multiple controller methods with the same @RequestMapping. The annotation is what differentiates them.

How can I configure MockMvc to use this custom mapping handler?


Solution

  • How can I configure MockMvc to use this custom mapping handler?

    As of Spring Framework 4.3.x, it is currently not possible to register a custom RequestMappingHandlerMapping with the standaloneSetup() builder for MockMvc.

    However, the team is considering adding such support in Spring Framework 5.0.

    See SPR-15472 for further details.