MockMvc WebAppConfiguration: Load servlet mappings in web.xml

你说的曾经没有我的故事 提交于 2019-11-30 23:25:20

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!