why my test is not using mocked static method and returning null

Viewed 33

I am trying to test the bussiness logic of a particular function.

code:

 @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    Context context = CStorage.getContext();
    HttpHeaders headers = request.getHeaders();
    Map<String,String> toPropogate=new HashMap<>();
    PropagatorCore.getInstance().inject(toPropogate,context);
    MultiValueMap<String,String> toSend= new LinkedMultiValueMap<>();
    HeaderUtils.logHeadersToSend(toPropogate);
    toSend.putAll(HeaderUtils.convertMultiMapList(toPropogate));
    headers.addAll(toSend);
    return execution.execute(request, body);
}

I want to use CStorage.getContext() method and return my dummy context that i created.

But CStorage.getContext() is a static method.

i tried following in my test :

  try (MockedStatic<CStorage> storage = Mockito.mockStatic(CStorage.class)) {

     storage.when(()->CStorage.getContext()).thenReturn(mockcontext);
     storage.verify(ContextStorage.getContext(),times(1));

    }
  clientHttpResponse = requestHeadersContextInterceptor.intercept(httprequest,body,execution);

Where mockcontext is my dummy context.

But when i call to requestHeadersContextInterceptor.intercept(httprequest,body,execution); function its giving me null values. also storage.verify(ContextStorage.getContext(),times(1)) fails saying no invocation found. Could you please suggest what am I missing and how to tackle this?

0 Answers
Related