0

I have some logic inside the interceptor's postHandle method to expose a header value to the my front end angular application. My question is how to test interceptors?

public class CustomResponseInterceptor implements HandlerInterceptor {
    private final String ADMIN_APP = "ADMIN_APP";
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
                           ModelAndView modelAndView) throws Exception {
        AdminApp adminApp = loadAdminApp();
        if(adminApp != null && adminApp.isValidAdminApp()){
            response.addHeader(ADMIN_APP, adminApp.getAppName());
            response.addHeader("Access-Control-Expose-Headers", ADMIN_APP);
        }
    }
}

Below is my testcase to check the add name is in header or not

@Test
void checkAdminAppNameInHeaderTest() throws Exception {
    HandlerInterceptor delegate = mock(HandlerInterceptor.class);
    new MappedInterceptor(null, delegate).postHandle(
            mock(HttpServletRequest.class), mock(HttpServletResponse.class), null, mock(ModelAndView.class));
    String adminAppName = response.getHeader(ADMIN_APP);
    assertNotNull(adminAppName );
}

However the header always returns null mostly because the request and response are mocked here. How can i traverse through interceptor logic so that the postHandle method is called?

softechie
  • 97
  • 2
  • 10

1 Answers1

0

Use the Spring Boot test slice annotation @WebMvcTest and test your application using MockMvc. With @WebMvcTest, Spring Boot populates all relevant Web-related beans for you inside the Spring TestContext.

This includes your HandlerInterceptor:

To test whether Spring MVC controllers are working as expected, use the @WebMvcTest annotation. @WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, HandlerInterceptor, WebMvcConfigurer, WebMvcRegistrations, and HandlerMethodArgumentResolver. Regular @Component and @ConfigurationProperties beans are not scanned when the @WebMvcTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.

Using MockMvc, you'll test against a mocked servlet environment, and your interceptor gets access to a proper HttpServletRequest, HttpServletResponse, and ModelAndView during test execution.

You'll have to invoke one of your @Controller/@RestController where the interceptor is registered.

Find more information on how to test your application with MockMvc here.

rieckpil
  • 10,470
  • 3
  • 32
  • 56