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?
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();
...
}
...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With