spring cloud is failing when I try to mock sleuth in unit tests

5k views Asked by At

I am facing some error when I try to mock objects like Tracer and Span in unit tests if I use Dalston.SR3 or Dalston.Release versions, but this problem doesn't happen if I use Camden.SR6 or Camden.SR7 versions.

Find an example code here

Microservice msvc-a is using Dalston version and has two test classes, where only is failing the class where I am trying to mock the Tracer and the Span objects.

Microservice msvc-b is using Camden version and has the same test classes.

At the same time, I can't understand this situation when I am in debug mode in STS and why I can't see any error trace or something like that... only a NullpointerException.

enter image description here

public class AbstractSpanAccessorTest {

    @MockBean
    private Tracer tracer;

    @MockBean
    private Span span;

    private Random random = new Random();

    @Before
    public void mockSpan() {
        long id = createId();
        Span spanMock = Span.builder().name("mock").traceId(id).spanId(id).build();
        doReturn(spanMock.traceIdString()).when(span).traceIdString();
        doReturn(span).when(tracer).getCurrentSpan();
        doReturn(span).when(tracer).createSpan(anyString());
    }

    private long createId() {
        return random.nextLong();
    }
}

2

There are 2 answers

0
Francisco José Martínez Páez On BEST ANSWER

It was my mistake. The correct way to mock the Span is:

 @Before
 public void mockSpan() {
     long id = createId();
     span = Span.builder().name("mock").traceId(id).spanId(id).build();
     doReturn(span).when(tracer).getCurrentSpan();
     doReturn(span).when(tracer).createSpan(anyString());
 }
0
Mitch1077487 On

Tracer wouldn't mock at all with Finchley.SR2 so I ended up with this:

Tracing tracing = Tracing.newBuilder().build();
Tracer tracer = tracing.tracer();