ResponseDeserializerByClass implements ResponseDeserializer { public <T> T deserialize(Response response) throws Exception { Class<T> type = (Class<T>) response.getExpectedType(); isTrue(classDeserializerRegistry.contains(type), CLASS_NOT_FOUND_ERROR, type); LOG.debug("Trying to deserialize response to Type: %s.", type); return classDeserializerRegistry.get(type).<T>deserialize( type, response.getExpectedGenericType(), response.asStream(), response.getCharset()); } ResponseDeserializerByClass(ComponentRegistry<Class<?>, Deserializer> classDeserializerRegistry); T deserialize(Response response);  }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenResponseExpectedTypeIsNotRecognized() throws Exception { when(mockResponse.getExpectedType()).thenReturn((Class)String.class); try { toTest.deserialize(mockResponse); } catch (Exception e) { assertEquals("Cannot deserialize response to class 'class java.lang.String', cancelling deserialization.\n" + "This happens after response's Content-Type based deserialization have failed deserializing the response because of an unknown or not present response Content-Type.\n" + "CRest has a predefined list of known classes for common data type (ei:primitives, InputStream, Reader etc...). These deserializers are used when CRest cannot deserialize the response based on the server response's content-type.\n" + "The method return type does not fall in the predefined list of known types. You can write your own deserializer and bind it as follow:\n" + "\n" + " CRest crest = new CRestBuilder().bindDeserializer(MyOwnTypeDeserializer.class, MyOwnType.class).build();\n" + "or, if the server can provide a Content-Type:\n" + " CRest crest = new CRestBuilder().bindDeserializer(MyOwnTypeDeserializer.class, \"the-content-type\").build();", e.getMessage()); throw e; } }
@Test public void shouldDeserializeWithAppropriateDeserializer() throws Exception { InputStream stream = mock(InputStream.class); when(mockResponse.getExpectedType()).thenReturn((Class)int.class); when(mockResponse.getExpectedGenericType()).thenReturn(int.class); when(mockResponse.getCharset()).thenReturn(UTF8); when(mockResponse.asStream()).thenReturn(stream); when(mockDeserializerInt.deserialize(int.class, int.class, stream, UTF8)).thenReturn(123); int actual = toTest.<Integer>deserialize(mockResponse); assertEquals(123, actual); }