我正在实现 HandlerInterceptor需要在处理对多个路径的请求之前/之后执行业务逻辑。我想通过模拟请求句柄生命周期来测试拦截器的执行。
以下是拦截器的注册方式:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/test*"/>
<bean class="x.y.z.TestInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
我不仅要测试
preHandle和
postHandle方法,但也映射到路径。
请您参考如下方法:
可以借助 JUnit 和 spring-test 编写以下测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:META-INF/spring.xml", ... })
public class InterceptorTest {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Test
public void testInterceptor() throws Exception{
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/test");
request.setMethod("GET");
MockHttpServletResponse response = new MockHttpServletResponse();
HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
HandlerInterceptor[] interceptors = handlerExecutionChain.getInterceptors();
for(HandlerInterceptor interceptor : interceptors){
interceptor.preHandle(request, response, handlerExecutionChain.getHandler());
}
ModelAndView mav = handlerAdapter. handle(request, response, handlerExecutionChain.getHandler());
for(HandlerInterceptor interceptor : interceptors){
interceptor.postHandle(request, response, handlerExecutionChain.getHandler(), mav);
}
assertEquals(200, response.getStatus());
//assert the success of your interceptor
}
HandlerExecutionChain填充了特定请求的所有映射拦截器。如果映射失败,拦截器将不会出现在列表中,因此不会被执行,最后的断言将失败。




