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

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

4

1 回答 1

2

我建议您将创建的方法拉出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
   }
}
于 2013-10-04T22:21:08.150 回答