如何测试Spring HandlerInterceptor Mapping

kpe*_*hev 3 mapping junit spring-mvc spring-test interceptor

我正在实现一个HandlerInterceptor需要在处理多个路径的请求之前/之后执行业务逻辑.我想通过模拟请求句柄生命周期来测试Interceptor的执行.

以下是拦截器的注册方式:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/test*"/>
        <bean class="x.y.z.TestInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)

我不仅要测试preHandlepostHandle方法,还要测试到路径的映射.

kpe*_*hev 10

可以在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

}
Run Code Online (Sandbox Code Playgroud)

HandlerExecutionChain填充了特定请求的所有映射拦截器.如果映射失败,拦截器将不会出现在列表中,因此不会执行,并且最后的断言将失败.


Sam*_*nen 6

Spring Framework 以Spring MVC 测试框架的形式为测试您的 Spring MVC 配置和组件提供专门的支持,自 Spring Framework 3.2 起可用(并且spring-test-mvc自 Spring Framework 3.1 起作为一个单独的项目)。

在第一个链接中,您将找到许多有关如何使用 Spring MVC 测试框架的示例。此外,您还可以在 SpringOne 2GX 的Spring 3.1 和 MVC 测试支持使用 Spring Framework 3.2 测试 Web 应用程序演示中找到 Rossen Stoyanchev(Spring MVC 测试框架的作者)的幻灯片。

我相信这些资源应该可以帮助您简洁地编写测试,但是如果您仍然需要帮助,请随时在此处回帖。

问候,

Sam(Spring TestContext Framework 的作者