模拟 Httpservletrequest 和 requestcontext
Mock Httpservletrequest and requestcontext
我正在尝试模拟 RequestContext
和 HttpServletRequest
classes/interfaces 但它们不起作用。
代码:
@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
异常。不确定这种测试方法的正确方法
需要模拟上下文的静态调用。
//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)
以便模拟的静态调用在调用时可用。
我正在尝试模拟 RequestContext
和 HttpServletRequest
classes/interfaces 但它们不起作用。
代码:
@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
异常。不确定这种测试方法的正确方法
需要模拟上下文的静态调用。
//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)
以便模拟的静态调用在调用时可用。