user09
user09

Reputation: 956

Mock Httpservletrequest and requestcontext

I am trying to mock RequestContext and HttpServletRequest classes/interfaces but they not working.

code:

@Override
public Object run() {

    String accessToken= "";

    ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    String requestedServiceUri = request.getRequestURI();

    //...

Mock I have written

//...

HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
RequestContext requestContext = Mockito.mock(RequestContext.class); 

when(request.getHeader("principal")).thenReturn("abcd");
when(request.getHeader("authorization")).thenReturn("authtoken");
when(request.getRequestURI()).thenReturn("abcd-tt/api/v1/softwaremanagement");

when(requestContext.getCurrentContext()).thenReturn(requestContext);
when(requestContext.getRequest()).thenReturn(request);

//...

I am getting MissingMethodInvocation exception. Not sure if this right way of testing this method

Upvotes: 1

Views: 10086

Answers (1)

Nkosi
Nkosi

Reputation: 247098

Need to mock the static call for the context.

//Arrange
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getHeader("principal")).thenReturn("abcd");
when(request.getHeader("authorization")).thenReturn("authtoken");
when(request.getRequestURI()).thenReturn("abcd-tt/api/v1/softwaremanagement");

RequestContext requestContext = Mockito.mock(RequestContext.class);
when(requestContext.getRequest()).thenReturn(request);

PowerMockito.mockStatic(RequestContext.class);    
when(RequestContext.getCurrentContext()).thenReturn(requestContext);

Do not forget to include

@PrepareForTest(RequestContext.class)

so that the mocked static calls will be available when invoked.

Upvotes: 2

Related Questions