Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Spring HandlerInterceptor Mapping

I am implementing a HandlerInterceptor that needs to execute business logic prior/after requests to several paths are handled. I want to test the execution of the Interceptor by mocking the request handle lifecycle.

Here is how the interceptor is registered:

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

I want to test not only the preHandle and postHandle methods, but the mapping to the path as well.

like image 503
kpentchev Avatar asked Jun 10 '14 12:06

kpentchev


1 Answers

The following test can be written with the help of JUnit and 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 is populated with all the mapped interceptors for the specific request. If the mapping is failing, the interceptor will not be present in the list and hence not executed and the assertion at the end will fail.

like image 117
kpentchev Avatar answered Nov 23 '22 23:11

kpentchev