Reputation: 83
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?
Upvotes: 2
Views: 2671
Reputation: 383
For those who's still in search, since Spring updated to version 5.0 (I believe) the custom MockMvc requestHandlerMapping configuration was introduced.
Example of usage:
MockMvcBuilders.standaloneSetup(new MyAwesomeController())
.setCustomHandlerMapping(() -> new MyAwesomeRequestMappingHandlerMapping())
.build();
Upvotes: 1
Reputation: 344
You can configure with override getRequestMappingHandlerMapping method of WebMvcConfigurerAdapter.
@Configuration
public class ConfigServletConfig extends WebMvcConfigurerAdapter {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = new VersionRangeRequestMappingHandlerMapping();
handlerMapping.setOrder(0);
return handlerMapping;
}
}
Upvotes: 0
Reputation: 31247
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.
Upvotes: 1