简体   繁体   中英

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

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.

在此处输入图片说明

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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