Httpservletrequest和requestcontex

Httpservletrequest和requestcontex

本文介绍了模拟Httpservletrequest和requestcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to mock RequestContext and HttpServletRequest classes/interfaces but they not working.

代码:

@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异常.不确定是否以正确的方式测试此方法

I am getting MissingMethodInvocation exception. Not sure if this right way of testing this method

推荐答案

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

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

别忘了包含

@PrepareForTest(RequestContext.class)

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

so that the mocked static calls will be available when invoked.

这篇关于模拟Httpservletrequest和requestcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:54