Mock Httpservletrequest and requestcontext

你。 提交于 2021-02-10 18:54:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!