Zipkin在单元测试中出错(无法模拟Span.baggageItems)

时间:2017-07-10 12:39:25

标签: spring spring-cloud spring-cloud-config

当我尝试在spring boot应用程序中运行unitTest时,我收到此错误。

java.lang.NullPointerException: null
at org.springframework.cloud.sleuth.Span.baggageItems(Span.java:381)
at org.springframework.cloud.sleuth.instrument.web.ZipkinHttpSpanInjector.inject(ZipkinHttpSpanInjector.java:27)
at org.springframework.cloud.sleuth.instrument.web.ZipkinHttpSpanInjector.inject(ZipkinHttpSpanInjector.java:15)
at org.springframework.cloud.sleuth.instrument.web.client.AbstractTraceHttpRequestInterceptor.publishStartEvent(AbstractTraceHttpRequestInterceptor.java:60)
at org.springframework.cloud.sleuth.instrument.web.client.TraceRestTemplateInterceptor.intercept(TraceRestTemplateInterceptor.java:52)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)

我注意到,当我将此版本用于 spring-cloud-dependencies 时,我才会收到此错误:

<spring-cloud.version>Dalston.RELEASE</spring-cloud.version>

但如果我使用此以前的版本:

<spring-cloud.version>Camden.SR6</spring-cloud.version>

一切都按照我的预期运作

为了避免上一版本出现此错误,我该怎么办?

单元测试在此类中进行了扩展,以模拟SpanAccessor

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

}

1 个答案:

答案 0 :(得分:1)

你为什么嘲笑跨度?这绝对没有意义。 Span也绝不是一个bean。您已经通过构建器创建了正常范围,您应该保留它。假设您已经设置了Boot上下文属性并且想要模拟tracer bean,那么您应该执行以下操作

public class AbstractSpanAccessorTest {
@MockBean
private Tracer tracer;

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).when(tracer).getCurrentSpan();
  doReturn(spanMock).when(tracer).createSpan(anyString());
}

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