我有办法模拟GoogleJsonResponseExceptions吗?

时间:2015-07-01 18:41:08

标签: google-api-java-client google-admin-sdk

我目前有一个不断轮询Google API的脚本 - 我已经集成了错误处理功能,并希望测试在收到此类错误时会发生预期的行为。

我想知道如何创建模拟GoogleJsonResponseExceptions - 特别是403来测试我的指数退避,我看到有一个HttpResponseException构建器 - http://javadoc.google-http-java-client.googlecode.com/hg/1.19.0/com/google/api/client/http/HttpResponseException.Builder.html

但我需要创建GoogleJsonResponseException类型的异常。我可以模拟诸如401(无效凭证)之类的东西,但403有点难吗?

请帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

看看这段代码,它显示了一种存档你想要的东西的方法:

 MockJsonFactory mockJsonFactory = new MockJsonFactory();

    HttpTransport transport = new MockHttpTransport() {
      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
        return new MockLowLevelHttpRequest() {
          @Override
          public LowLevelHttpResponse execute() throws IOException {
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            response.setStatusCode(408);
            response.setContent("{\"error\":\"Timeout\"}");
            return response;
          }
        };
      }
    };
    HttpRequest httpRequest =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    httpRequest.setThrowExceptionOnExecuteError(false);
    HttpResponse httpResponse = httpRequest.execute();
    GoogleJsonResponseException googleJsonResponseException =

答案 1 :(得分:0)

幸运的是,Google API提供了一种创建模拟GoogleJsonResponseExceptions的方法:

JsonFactory jsonFactory = new MockJsonFactory();
GoogleJsonResponseException testException = GoogleJsonResponseExceptionFactoryTesting.newMock(jsonFactory, HttpStatus.FORBIDDEN.value(), "Test Exception");