@After public void afterMethod() { resetTracingAndMdc(); }
@Before public void beforeMethod() throws Exception { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); callableMock = mock(Callable.class); throwExceptionDuringCall = false; currentSpanStackWhenCallableWasCalled = new ArrayList<>(); currentMdcInfoWhenCallableWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenCallableWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenCallableWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(callableMock).call(); resetTracingAndMdc(); }
@DataProvider(value = { "true", "false" }) @Test public void call_handles_tracing_and_mdc_info_as_expected(boolean throwException) throws Exception { // given throwExceptionDuringCall = throwException; Tracer.getInstance().startRequestWithRootSpan("foo"); Deque<Span> spanStack = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfo = MDC.getCopyOfContextMap(); CallableWithTracingAndMdcSupport instance = new CallableWithTracingAndMdcSupport( callableMock, spanStack, mdcInfo ); resetTracingAndMdc(); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isEmpty(); // when Throwable ex = catchThrowable(() -> instance.call()); // then verify(callableMock).call(); if (throwException) assertThat(ex).isNotNull(); else assertThat(ex).isNull(); assertThat(currentSpanStackWhenCallableWasCalled.get(0)).isEqualTo(spanStack); assertThat(currentMdcInfoWhenCallableWasCalled.get(0)).isEqualTo(mdcInfo); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isEmpty(); }