1

我正在尝试模拟RequestContextHttpServletRequest类/接口,但它们不起作用。

代码:

@Override
public Object run() {

    String accessToken= "";

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

    String requestedServiceUri = request.getRequestURI();

    //...

模拟我写的

//...

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);

//...

我得到了MissingMethodInvocation例外。不确定测试此方法的正确方法是否正确

4

1 回答 1

2

需要模拟上下文的静态调用。

//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);

不要忘记包括

@PrepareForTest(RequestContext.class)

以便在调用时可以使用模拟的静态调用。

于 2018-07-27T20:39:22.117 回答