使用SpringBootTest

时间:2020-06-03 11:54:11

标签: spring-boot groovy spring-boot-test spring-cloud-sleuth

我正在从Spring Boot 1.5.21迁移到2.2.5,并且在此过程中还从spring-boot-cloud版本Edgware.SR6迁移到Hoxton.SR3。这一举动迫使我放弃了侦探自己的示踪剂/跨度模型的实现,并勇敢地拥抱了新模型。但是,我的控制器集成测试有问题。

我有一个名为Edge的微服务,其主类为EdgeApplication,并且我使用Spock作为测试框架。 我的代码包括以下测试类:

@ContextConfiguration(classes = EdgeApplication.class)
@SpringBootTest(classes = EdgeApplication.class)
@ActiveProfiles(profiles = ["test"])
@AutoConfigureMockMvc
class VerificationCodeControllerSpecIT extends Specification {

  @Autowired
  MockMvc mockMvc

  def setup() {
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build()
  }

  def "Generate change password verification code"() {
    // Some code calling a PrincipalController via mockMvc.perform()
  }
}

以前,在Spring Boot 1.5.21中,当调用到达PrincipalController时,会初始化一个默认的带有span的跟踪上下文。现在,在Spring Boot 2中不是这种情况。我必须强调,PrincipalController中缺少上下文仅在测试代码中发生,而在微服务的实际运行中没有发生。

为什么更改此行为,如何恢复旧的行为,即调用控制器时具有默认的span跟踪上下文?

我添加了一个演示项目: Demo 您将能够运行集成测试,并在调试中看到控制器tracer.currentSpan()中为空(在正常项目运行时包含值)

2 个答案:

答案 0 :(得分:2)

在Spring Boot 1.5.21中,spring-cloud-sleuth的最新受支持版本是1.3.6.RELEASE。

在旧版本中,Sleuth曾经有拦截器:'TraceHandlerInterceptor'用于在Servlet调度程序触发该拦截器时创建跨度。

在1.5.21版上运行Spring Boot测试时,MockMvc初始化TestDispatcherServlet会触发上述拦截器。

作为与Brave对齐的HTTP工具的一部分,该拦截器已被删除。

使用MockMvc时,必须明确配置过滤器链。 您的MockMvc缺少TracingFilter

答案 1 :(得分:0)

如果它与Spring Security有关,那么您应该使用Demo on DB Fiddle。示例:

MockMvcBuilders.webAppContextSetup(this.wac)
   .apply(SecurityMockMvcConfigurers.springSecurity())
   .build();