我正在使用 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 映射,或者有什么聪明的方法可以解决这个问题吗?提前致谢。
Edit:
A 类似的问题这里表明我需要的是不可能的,但我没有更改源代码的权限,所以我无法修改模板或HandlerInterceptor
.
我正在使用 MockMvc 和 MockMvc HtmlUnitDriver 来测试应用程序中的导航流程。我遇到了 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)