繁体   English   中英

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

[英]How to test a Spring Boot handler Interceptor

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

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

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

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

所以我们想测试拦截器,但我们不想真正启动应用程序,因为有很多依赖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());
  }
}

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

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

你可以创建一个这样的测试:

@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;
        }

    }

}

笔记

  • 只有在设置SpringBootTest.WebEnvironment.RANDOM_PORT时,拦截器才有效
  • 您必须提供足够的配置,以便执行拦截器
  • 要加快测试速度,您可以排除不需要的bean和配置,请参阅示例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertTrue;

@SpringBootTest()
class LoggingInterceptorConfigurationTest {

    @Autowired
    private RequestMappingHandlerMapping mapping;

    @Test
    public void LoggingInterceptorShouldBeApplied() throws Exception {

        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/example");

        HandlerExecutionChain chain = mapping.getHandler(request);

        assert chain != null;
        Optional<HandlerInterceptor> LoggingInterceptor = chain.getInterceptorList()
                .stream()
                .filter(LoggingInterceptor.class::isInstance)
                .findFirst();

        assertTrue(LoggingInterceptor.isPresent());
    }

    @Test
    public void LoggingInterceptorShouldNotBeAppliedToHealthURL() throws Exception {

        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/health");

        HandlerExecutionChain chain = mapping.getHandler(request);

        assert chain != null;
        Optional<HandlerInterceptor> LoggingInterceptor = chain.getInterceptorList()
                .stream()
                .filter(LoggingInterceptor.class::isInstance)
                .findFirst();

        assertTrue(LoggingInterceptor.isEmpty());
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM