Home > database >  Getting NullPointerException tracer.currentSpan() is Null
Getting NullPointerException tracer.currentSpan() is Null

Time:03-25

I'm trying to create test case for given class and want to return traceId value but getting trace.currentSpan() is null.

Here is my Class

public class ConsumerService{

private final Tracer tracer;

@Autowired
private RequestService requestService;

public void consumerProductionRequest(DisclaimerRequest disclaimerRequest){
String traceId=tracer.currentSpan.context().traceId();
log.info(traceId);
if(disclaimerRequest.getReqId()==null){
disclaimerRequest.setReqId(UUID.randomUUID().toString());
}
}
}

//Test Class
@ExtendWith(MockitoExtension.class)
class ConsumerServiceTest{

@InjectMocks
ConsumerService consumerService;

@Autowired
Tracer tracer;

@Test
void Test(){
    Tracer tracer=Mockito.mock(Tracer.class);
    String traceId;
    Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);
    DisclaimerRequest disclaimerRequest=new DisclaimerRequest();
    consumerService.consumerProductionRequest(disclaimerRequest);
}
}

Why am I getting tracer.currentSpan() null. I'm using JUnit 5 and new in this. Please someone help me to solve this.

CodePudding user response:

Here, in your test class:

@Autowired
Tracer tracer;

Turn that into

@Mock
Tracer tracer;

(and add the corresponding import to Mockito). You want that Mockito creates a mock object, and then inserts that into your object under test. Also note that your test method itself redefines tracer, thus shadowing whatever else you did on class level. Therefore that spec for tracer within the test method won't have any effect on the mocked Tracer instance that already got injected into your object under test.

CodePudding user response:

Tracer tracer=Mockito.mock(Tracer.class);
String traceId;
Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);

tracer will be mock and you can see it in debug or just simply print it. also each method returns null because you didn't specify which method will return value because spring context does not work in unit tests. In integration tests you can autowire it.

Mockito.when(tracer.getCurrentSpan()).thenReturn(someSpan);
Mockito.when(tracer.getCurrentSpan().getContext()).thenReturn(someContext);
String traceId;
Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);

You have to mock getCurrentSpan and getContext methods that will solve your problem. Also you can not autowire it just use @Mock annotation. Spring context does not exist in unit tests so it won't be autowired. Spring related codes won't work. Integration test runs the spring context for you and you can autowire it.

  • Related