I'm writing integration tests using MockMvc, and I'm wondering if there's a way to load servlet mappings from web.xml (which normally shouldn't matter).
I have a custom HandlerInteceptor
that matches the request URI (from HttpServletRequest
) against a template (using AntPathMatcher
).
In web.xml, I define servlet mappings like this (with a corresponding mobile-context.xml):
<servlet-mapping>
<servlet-name>mobileServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
So when a controller defines a mapping like "/operation"
, requests should really be made to "/services/operation"
. My custom HandlerInterceptor
matches URI requests against a template like "/**/services/{operationName}/**"
.
My application works perfectly on Tomcat. However, in @ContextConfiguration, I can only specify mobile-context.xml since web.xml is not a spring config file. Thus, MockMvc only allows me to make requests to "/operation"
and not "/services/operation"
, causing my HandlerInterceptor
to throw an exception.
Is there any way to get MockMvc to register the servlet mappings, or any clever ways around this? Thanks in advance.
Edit:
A similar question here suggests what I need is not possible, but I don't have permission to change the source code, so I can't modify the template or the HandlerInterceptor
.
There is no way to load the web.xml mappings. However you can explicitly set the context path, servlet path, and path info on the request. See the Javadoc for those methods in MockHttpServletRequestBuilder.
I am using MockMvc and MockMvcHtmlUnitDriver to test navigation flow in my application. I faced the issue of MockMvc not being able to load my javascript resources because my servlet mapping was
<url-pattern>/ui/*</url-pattern>
Because my navigation flows were a series of posts and gets, i could not simply set the defaultRequest on the MockMvcBuilder. I solved my problem by creating a MockMvcConfigurer:
public class ServletPathConfigurer implements MockMvcConfigurer {
private final String urlPattern;
private final String replacement;
public ServletPathConfigurer(String urlPattern, String replacement) {
super();
this.urlPattern = urlPattern;
this.replacement = replacement;
}
@Override
public RequestPostProcessor beforeMockMvcCreated(
ConfigurableMockMvcBuilder<?> builder,
WebApplicationContext context) {
return new RequestPostProcessor(){
@Override
public MockHttpServletRequest postProcessRequest(
MockHttpServletRequest request) {
request.setRequestURI(StringUtils.replace(request.getRequestURI(), urlPattern, replacement, 1));
request.setServletPath(StringUtils.replace(request.getServletPath(), urlPattern, replacement, 1));
return request;
}
};
}
and then adding it to each of my integration tests:
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(new ServletPathConfigurer("/ui",""))
.alwaysDo(print())
.build();
来源:https://stackoverflow.com/questions/25270135/mockmvc-webappconfiguration-load-servlet-mappings-in-web-xml