Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init a default trace context with span in controller when using SpringBootTest

I'm making a move from Spring Boot 1.5.21 to 2.2.5, and in the process also moving from spring-boot-cloud version Edgware.SR6 to Hoxton.SR3. This move forced me to ditch the sleuth's own implementation of tracer/span model and embrace the new model from brave. However, I have an issue with my controller integration tests.

I have a microservice called Edge with a main class called EdgeApplication and I'm using Spock as a testing framework. My code includes the following test class:

@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()
  }
}

Previously, in Spring Boot 1.5.21, when The call got to the PrincipalController, a default trace context with span was initialized. Now, in Spring Boot 2, this is not the case. I must emphasise that this lack of context in the PrincipalController only happens in test code, and not in a real run of the microservice.

Why this behavior changed and how can I restore the old behavior, i.e. have a default trace context with span when the controller is called?

I added a demo project: Demo You will be able to run the integration test and in debug see that in the controller tracer.currentSpan() is null (while containing a value on normal project run)

like image 459
Eyal Ringort Avatar asked Oct 15 '22 03:10

Eyal Ringort


1 Answers

At Spring Boot 1.5.21 the latest supported version for spring-cloud-sleuth was 1.3.6.RELEASE.

In the old version, Sleuth used to have interceptor: 'TraceHandlerInterceptor' to create a span when the Servlet dispatcher triggers this interceptor.

While running your Spring Boot test at version 1.5.21 the MockMvc init TestDispatcherServlet that triggers the above interceptor.

As part of aligned HTTP instrumentation with Brave, this interceptor was removed.

when using MockMvc it's necessary to explicitly configure your filter Chain. your MockMvc is missing the TracingFilter

like image 68
Tzachi Strugo Avatar answered Nov 29 '22 08:11

Tzachi Strugo