我正在尝试模拟RequestContext
和HttpServletRequest
类/接口,但是它们不起作用。
代码:
@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
异常。不确定是否以正确的方式测试此方法
答案 0 :(得分:1)
需要模拟对上下文的静态调用。
//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)
,以便在调用时可以使用模拟的静态调用。