gpt4 book ai didi

spring-mvc - 如何测试 Spring HandlerInterceptor 映射

转载 作者:行者123 更新时间:2023-12-04 16:31:16 25 4
gpt4 key购买 nike

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

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

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/test*"/>
<bean class="x.y.z.TestInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

我不仅要测试 preHandlepostHandle方法,但也映射到路径。

最佳答案

可以借助 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填充了特定请求的所有映射拦截器。如果映射失败,拦截器将不会出现在列表中,因此不会被执行,最后的断言将失败。

关于spring-mvc - 如何测试 Spring HandlerInterceptor 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24140494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com