4

我正在使用 MockMvc 编写集成测试,我想知道是否有办法从 web.xml 加载 servlet 映射(这通常无关紧要)。

我有一个HandlerInteceptor将请求 URI(来自HttpServletRequest)与模板(使用AntPathMatcher)相匹配的自定义。

在 web.xml 中,我定义了这样的 servlet 映射(带有相应的 mobile-context.xml):

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

所以当一个控制器定义一个像这样的映射时"/operation",请求真的应该被发送到"/services/operation"。我的自定义HandlerInterceptor将 URI 请求与"/**/services/{operationName}/**".

我的应用程序在 Tomcat 上运行良好。但是,在@ContextConfiguration 中,我只能指定mobile-context.xml,因为web.xml 不是spring 配置文件。因此,MockMvc 只允许我向"/operation"而不是发出请求"/services/operation",从而导致我HandlerInterceptor抛出异常。

有没有办法让 MockMvc 注册 servlet 映射,或者有什么聪明的方法解决这个问题?提前致谢。

编辑:这里有一个类似的问题表明我需要的东西是不可能的,但我没有更改源代码的权限,所以我不能修改模板或HandlerInterceptor.

4

2 回答 2

4

我正在使用 MockMvc 和 MockMvcHtmlUnitDriver 在我的应用程序中测试导航流程。我遇到了 MockMvc 无法加载我的 javascript 资源的问题,因为我的 servlet 映射是

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

因为我的导航流程是一系列帖子和获取,所以我不能简单地在 MockMvcBuilder 上设置 defaultRequest。我通过创建 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();
于 2015-04-28T13:31:01.633 回答
1

无法加载 web.xml 映射。但是,您可以显式设置请求的上下文路径、servlet 路径和路径信息。有关 MockHttpServletRequestBuilder 中的这些方法,请参阅 Javadoc。

于 2014-08-19T18:50:11.470 回答