【问题标题】:how to fetch response from requestContext.abortwith() method如何从 requestContext.abortwith() 方法获取响应
【发布时间】:2017-11-03 02:10:32
【问题描述】:
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 时,如何获取 ServerResponse 对象内的 errorCode 集。

 @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.
  }
}

【问题讨论】:

  • 能否请您附上您当前的测试尝试。答案取决于您的测试设置。这是an option。
  • 添加了测试类和描述。

标签: java spring-mvc junit mockito


【解决方案1】:

您需要的是ArgumentCaptor:

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

这会检查方法 abortWith 是否只被调用了一次(曾经是 verify 的默认值),并将调用它的参数存储在 ArgumentCaptor 中,您可以从中获取它...

Response response = argumentCaptor.getValue();

更多详情请参阅JavaDoc。

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

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多