问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/51564904/mock-httpservletrequest-and-requestcontext