MockMvc WebAppConfiguration: Loading servlet mappings in web.xml

I am writing integration tests using MockMvc and I wonder if there is a way to load servlet mappings from web.xml (which usually doesn't matter).

I have a custom HandlerInteceptorone that matches the request URI (from HttpServletRequest) to the template (using AntPathMatcher).

In web.xml, I define these servlet mappings (with the corresponding mobile-context.xml):

<servlet-mapping>
    <servlet-name>mobileServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

Therefore, when the controller determines such a mapping as "/operation", requests really need to be made in "/services/operation". My custom HandlerInterceptormatches URI requests for a type template "/**/services/{operationName}/**".

My application works fine on Tomcat. However, in @ContextConfiguration I can only specify the mobile-context.xml file, since web.xml is not a spring configuration file. This way, MockMvc allows me to make requests only "/operation", and not "/services/operation", causing my to HandlerInterceptorthrow an exception.

Is there a way to get MockMvc to register servlet mappings, or any smart ways around this? Thanks in advance.

Edit: A similar question here suggests what I need is impossible, but I do not have permission to modify the source code, so I can not change the template or HandlerInterceptor.

+3
source share
2 answers

web.xml. , . . Javadoc MockHttpServletRequestBuilder.

+2

MockMvc MockMvcHtmlUnitDriver . , MockMvc javascript,

<url-pattern>/ui/*</url-pattern>

, defaultRequest MockMvcBuilder. , 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;
        }
    };
}

:

MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .apply(new ServletPathConfigurer("/ui",""))
            .alwaysDo(print())
            .build();
+3

Source: https://habr.com/ru/post/1673111/


All Articles