如何测试 Spring Boot 处理程序拦截器

sth*_*der 9 java spring spring-mvc spring-boot spring-boot-test

我们正在尝试使用 spring boot 1.4.0 版对我们的 spring boot 应用程序中的拦截器进行集成测试,但不确定如何;这是我们的应用程序设置

@Configuration
@EnableAutoConfiguration()
@ComponentScan
public class Application extends SpringBootServletInitializer {
  @Override
  protected SpringApplicationBuilderconfigure(SpringApplicationBuilder application) {
  return application.sources(Application.class);
}
Run Code Online (Sandbox Code Playgroud)

然后我们通过扩展 WebMvcConfigurerAdapter 来定制 webmvc

@Configuration
public class CustomServletContext extends WebMvcConfigurerAdapter{
  @Override
  public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(testInterceptor).addPathPatterns("/testapi/**");
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我们想测试拦截器,但我们不想真正启动应用程序,因为有很多依赖bean需要读取外部定义的属性文件来构造

我们尝试了以下方法

@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());
  }
}
Run Code Online (Sandbox Code Playgroud)

但它改变了 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'requestMappingHandlerMapping' is defined

我们是否需要创建一个 requestMappingHandlerMapping 的 bean 来测试拦截器?在 spring boot 中有什么神奇的方法可以做到这一点吗?

Pet*_*nto 4

您可以创建这样的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = { MyIncludedConfig.class })
@ActiveProfiles("my_enabled_profile")
public class BfmSecurityInterceptorTest2 {

    public static final String TEST_URI = "/test";
    public static final String RESPONSE = "test";

    // this way you can provide any beans missing due to limiting the application configuration scope
    @MockBean
    private DataSource dataSource;

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void testInterceptor_Session_cookie_present_Authorized() throws Exception {

        ResponseEntity<String> responseEntity = testRestTemplate.getForEntity(TEST_URI, String.class);

        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(responseEntity.getBody()).isEqualTo(RESPONSE);

    }

    @SpringBootApplication
    @RestController
    public static class TestApplication {

        @GetMapping(TEST_URI)
        public String test() {
            return RESPONSE;
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

笔记

  • 仅当设置 SpringBootTest.WebEnvironment.RANDOM_PORT 时,拦截器才起作用
  • 您必须提供足够的配置才能执行您的拦截器
  • 为了加快测试速度,您可以排除不需要的 bean 和配置,请参阅示例