Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot 2.0.5.RELEASE - sleuth and mockito

I have tried to sort this out for a week, but no luck at all. The issue is with the unit tests.

This is the class that I am trying to test:

import brave.Span;
import brave.Tracer;

@Service
public class InternetBackEndRestClient {

    @Autowired
    private Tracer tracer;

  public PasswordJwtResponse generatePassworJwt(PasswordJwtRequest passwordJwtRequest, String traceId) throws LogonProxyException {
      log.info("{\"Starting method\": \"generatePassworJwt\", \"input\": {} }", passwordJwtRequest);

    Span newSpan = tracer.nextSpan().name("spanPasswordJwtResponse");
    ...
  }
}

How can I do the unit test? Brave.Tracer is a final class so that I cannot mock it. Is there anyway to set up a context? or mock Tracer?

@RunWith(MockitoJUnitRunner.class)
public class InternetBackEndRestClientTest {

   @InjectMocks
   private InternetBackEndRestClient internetBackEndRestClient; 

   @Mock
   private Tracer tracer; 

   @Test
   public void generatePassworJwt_test() { 
      internetBackEndRestClient.generatePassworJwt(...);
      ....
   }
}

Could anyone help me please?

like image 848
Fany Castro Vizoso Avatar asked Dec 10 '25 17:12

Fany Castro Vizoso


2 Answers

Here is the solution that worked for me:

@RunWith(MockitoJUnitRunner.class)
public class InternetBackEndRestClientTest {

    private static final String TRACEID = "12345678901234567890123456789012";

    @InjectMocks
    private InternetBackEndRestClient internetBackEndRestClient;

    @Mock
    private Tracer tracer;
   @Mock
    private Span span;

    @Before
    public void setUp()  {

        MockitoAnnotations.initMocks(this);

        when(tracer.nextSpan()).thenReturn(span);
        when(tracer.nextSpan().name("spanPasswordJwtResponse"))
           .thenReturn(span);
        when(span.start()).thenReturn(span);

        Tracing tracing = Tracing.newBuilder().build();
        doReturn(tracing.tracer().withSpanInScope(span))
             .when(tracer).withSpanInScope(span);
        doNothing().when(span).finish();

        ...
    }
    ...
}
like image 158
Fany Castro Vizoso Avatar answered Dec 12 '25 21:12

Fany Castro Vizoso


You can manually set the span and trace id using TraceContext.newBuilder() in a test and past the Tracer into the class being tested.

Tracer tracer = Tracing.newBuilder().build().tracer();
TraceContext ctx = TraceContext.newBuilder().traceId(10L).spanId(10L).build();
Span span = tracer.toSpan(ctx);
tracer.withSpanInScope(span);

This might be a bit lighter than mocking the Tracer class

like image 45
Matthew.Lothian Avatar answered Dec 12 '25 21:12

Matthew.Lothian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!