如何从requestContext.abortwith()方法获取响应

时间:2017-11-03 02:10:33

标签: java spring-mvc junit mockito

Class Permission implements ContainerRequestContext
{

    @context
    HttpServletRequest servletRequest;

    public void filter(ContainerRequestContext containerRequestContext) throws IOException 
    {
        String Path=servletRequest.getPathInfo;

        int id=containerRequestContext.getId;

        if(id==null){
            containerRequestContext.abortWith(new ServerResponse(ExceptionUtil.getErrorMessageObject(...),errorCode,new Header<Object>()));
        }
    }
}

出于测试目的,

当我们设置id = null时,如何获取errorCode对象中的ServerResponse集。

 @RunWith(MockitoJUnitRunner.class)
    class Test {

  @InjectMocks
  private Permission permission;
  @Mock
  private HttpServletRequest servletRequest;
  @Mock
  private ContainerRequestContext containerRequestContext;

  @Test
  public void test()
  {
      when(servletRequest.getPathInfo()).thenReturn("/getid");
      when(containerRequestContext.getId()).thenReturn(null);
      permission.filter(containerRequestContext);

      Response r = //Need the code. How to get the Response that i have set on permission class when id=null so that i can fetch the errorCode from that.
  //With that erroCode i can write my test methods.
  }
}

1 个答案:

答案 0 :(得分:0)

您需要的是ArgumentCaptor

ArgumentCaptor<Response> argumentCaptor = ArgumentCaptor.forClass(Response.class);
verify(containerRequestContext).abortWith( argumentCaptor.capture() );

这检查方法abortWith是否已被调用一次(一次是verify的默认值)并将已调用的参数存储在ArgumentCaptor中,您可以从中{通过......获得它。

Response response = argumentCaptor.getValue();

有关详细信息,请参阅JavaDoc

当然,还有其他方法(例如,您可以使用Answer),但它们并不那么容易。