loonyuni
loonyuni

Reputation: 1473

Is there a way for me to mock GoogleJsonResponseExceptions?

I currently have a script that continuously polls a Google API - I have integrated error handling, and would like to test that the expected behavior ensues when receiving such errors.

I would like to know how to create mock GoogleJsonResponseExceptions - specifically 403 to test my exponential backoff, I saw that there is an HttpResponseException builder - http://javadoc.google-http-java-client.googlecode.com/hg/1.19.0/com/google/api/client/http/HttpResponseException.Builder.html

But I need to create exceptions of type GoogleJsonResponseException. I can mock things such as 401 (invalid credentials), but 403 is a little harder to do?

Please help, thanks!

Upvotes: 0

Views: 1360

Answers (2)

Andreas Rudich
Andreas Rudich

Reputation: 121

Fortunately the Google API offers a way to create mock GoogleJsonResponseExceptions:

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

Upvotes: 2

Victor
Victor

Reputation: 3978

Take a look at this code, it shows a way to archive what are you looking for:

 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 =

Upvotes: 2

Related Questions