【问题标题】:How to write EasyMock Unit test for http call timeout?如何为 http 调用超时编写 EasyMock 单元测试?
【发布时间】:2013-10-04 17:12:12
【问题描述】:
    final HttpResponse response = this.call(queryUri);
        entity = response.getEntity();public HttpResponse call(final URI queryUri) throws Exception
{
    Future<HttpResponse> futureResponses = executor.submit(new Callable<HttpResponse>()
    {
        @Override
        public HttpResponse call() throws Exception
        {
            final HttpGet httpget = new HttpGet(queryUri);
            return httpclient.execute(httpget);
        }
    });
    return futureResponses.get(A9_CALL_TIMEOUT, TimeUnit.MILLISECONDS);
}

final HttpResponse response = this.call(queryUri);
entity = response.getEntity();
parse(entity.getcontent());

想知道如何模拟所有对象,有人可以为我提供测试类的可行代码吗?

【问题讨论】:

  • 你尝试了什么,得到了什么结果?

标签: junit easymock


【解决方案1】:

我建议您将 Callable 的创建拉到受保护的方法中。

public Callable<HttpResponse> createCallable(String queryUri){
  return new Callable<HttpResponse>(){
    @Override
    public HttpResponse call() throws Exception
    {
        final HttpGet httpget = new HttpGet(queryUri);
        return httpclient.execute(httpget);
    }
});

}

我认为您实际上不需要 EasyMock 来进行此测试。事实上,没有它可能会更容易。在您的测试中,您可以覆盖此方法以返回测试存根。我认为如果 get 超时,那么它会抛出 TimeoutException 而不会真正取消作业。所以我认为你只需要捕获 TimeoutException 以确保一切正常。

所以也许你的模拟只需要为A9_CALL_TIMEOUT 加上一些额外的软糖因素就睡了。

@Test
public void testTimeout(){
    Subclass sut = new Subclass(){

          @Override
          public Callable<HttpResponse> createCallable(String queryUri){

            return new Callable<HttpResponse>(){
                  @Override
                   public HttpResponse call() throws Exception{
                        try{
                            Thread.sleep(A9_CALL_TIMEOUT *2);
                        catch(InterruptException e) {}
                   }
          });

   };
   //you can also use Junit ExpectedException rule instead
   // of the try catch here
   try{

      sut.runQueryMethodWithExecutor();
      fail("should throw timeout");
   }catch(TimeoutException e){
       //expected
   }
}

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 2010-11-16
    • 2018-01-17
    • 2012-01-06
    • 2019-03-17
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多