DefaultingJsonResponseHandler implements ResponseHandler<T, RuntimeException> { @Override public T handle(Request request, Response response) { if (!successfulResponseCodes.contains(response.getStatusCode())) { return defaultValue; } String contentType = response.getHeader(CONTENT_TYPE); if (contentType != null && !MediaType.parse(contentType).is(MEDIA_TYPE_JSON)) { return defaultValue; } try { return jsonCodec.fromJson(ByteStreams.toByteArray(response.getInputStream())); } catch (Exception e) { return defaultValue; } } private  DefaultingJsonResponseHandler(JsonCodec<T> jsonCodec, T defaultValue); private  DefaultingJsonResponseHandler(JsonCodec<T> jsonCodec, T defaultValue, int firstSuccessfulResponseCode, int... otherSuccessfulResponseCodes); static DefaultingJsonResponseHandler<T> createDefaultingJsonResponseHandler(JsonCodec<T> jsonCodec, T defaultValue); static DefaultingJsonResponseHandler<T> createDefaultingJsonResponseHandler(JsonCodec<T> jsonCodec, T defaultValue, int firstSuccessfulResponseCode, int... otherSuccessfulResponseCodes); @Override T handleException(Request request, Exception exception); @Override T handle(Request request, Response response);  }
@Test public void testValidJson() { User user = new User("Joe", 25); String json = codec.toJson(user); User response = handler.handle(null, mockResponse().contentType(JSON_UTF_8).body(json).build()); assertEquals(response.getName(), user.getName()); assertEquals(response.getAge(), user.getAge()); }
@Test public void testInvalidJson() { String json = "{\"age\": \"foo\"}"; User response = handler.handle(null, mockResponse().contentType(JSON_UTF_8).body(json).build()); assertSame(response, DEFAULT_VALUE); }
@Test public void testSyntacticallyInvalidJson() { String json = "foo"; User response = handler.handle(null, mockResponse().contentType(JSON_UTF_8).body(json).build()); assertSame(response, DEFAULT_VALUE); }
@Test public void testNonJsonResponse() { User response = handler.handle(null, mockResponse().contentType(PLAIN_TEXT_UTF_8).body("hello").build()); assertSame(response, DEFAULT_VALUE); }
@Test public void testJsonErrorResponse() { String json = "{\"error\": true}"; User response = handler.handle(null, mockResponse().status(INTERNAL_SERVER_ERROR).contentType(JSON_UTF_8).body(json).build()); assertSame(response, DEFAULT_VALUE); }
@Test public void testJsonReadException() throws IOException { InputStream inputStream = mock(InputStream.class); IOException expectedException = new IOException("test exception"); when(inputStream.read()).thenThrow(expectedException); when(inputStream.read(any(byte[].class))).thenThrow(expectedException); when(inputStream.read(any(byte[].class), anyInt(), anyInt())).thenThrow(expectedException); User response = handler.handle(null, mockResponse() .contentType(JSON_UTF_8) .body(inputStream) .build()); assertSame(response, DEFAULT_VALUE); }