we are trying to do an intergration test our interceptors in our spring boot application using spring boot version 1.4.0, but not sure how; here is our application setting
@Configuration
@EnableAutoConfiguration()
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilderconfigure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
we then customed out webmvc by extending WebMvcConfigurerAdapter
@Configuration
public class CustomServletContext extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(testInterceptor).addPathPatterns("/testapi/**");
}
}
so we wanna to test the interceptor, but we don't wanna really start the application, cause there are many dependency beans that need to read a externally defined property files to construct
we have tried the following
@SpringBootTest(classes = CustomServletContext.class)
@RunWith(SpringRunner.class)
public class CustomServletContextTest {
@Autowired
private ApplicationContext applicationContext;
@Test
public void interceptor_request_all() throws Exception {
RequestMappingHandlerMapping mapping = (RequestMappingHandlerMapping) applicationContext
.getBean("requestMappingHandlerMapping");
assertNotNull(mapping);
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/test");
HandlerExecutionChain chain = mapping.getHandler(request);
Optional<TestInterceptor> containsHandler = FluentIterable
.from(Arrays.asList(chain.getInterceptors()))
.filter(TestInterceptor.class).first();
assertTrue(containsHandler.isPresent());
}
}
but it alters org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'requestMappingHandlerMapping' is defined
Do we need to create a bean of requestMappingHandlerMapping to test the interceptors? is there any magical way to do this in spring boot ?
TestInterceptor
? If so, create an instance of it and call theHandlerInterceptor
methods and verify outcome. That's called Unit Testing, i.e. testing the Unit, aka theTestInterceptor
. – Biathlon"/testapi/**"
pattern correctly, i.e. you want to test Spring? Again, why? – Biathlon/testapi/foo/bar
? If no, use/testapi/*
. If yes, use/testapi/**
. – Biathlon