ResponseDeserializerComposite implements ResponseDeserializer { public <T> T deserialize(Response response) throws Exception { IllegalArgumentException deserializationException = null; for(ResponseDeserializer deserializer : delegates){ try { return deserializer.<T>deserialize(response); } catch (IllegalArgumentException e) { LOG.trace("Deserializer %s can't handle response, trying with next one", deserializer); deserializationException = e; } } LOG.debug(deserializationException, "Cannot deserialize response with given deserialize list: %s. Last exception: %s", delegates, deserializationException.getMessage()); throw new CRestException(deserializationException.getMessage(), deserializationException); } ResponseDeserializerComposite(ResponseDeserializer... delegates); T deserialize(Response response);  }
@Test(expected = CRestException.class) public void shouldIterateOverResponseDeserializersAsLongAsIllegalArgumentExceptionIsThrown() throws Exception { Exception e1 = new IllegalArgumentException(); Exception e2 = new IllegalArgumentException(); when(mockResponseDeserializer1.deserialize(mockResponse)).thenThrow(e1); when(mockResponseDeserializer2.deserialize(mockResponse)).thenThrow(e2); try { toTest.deserialize(mockResponse); fail(); } catch (Exception e) { assertSame(e2, e.getCause()); throw e; } }
@Test public void shouldIterateOverResponseDeserializersUntilSuccess() throws Exception { when(mockResponseDeserializer1.deserialize(mockResponse)).thenThrow(new IllegalArgumentException()); when(mockResponseDeserializer2.deserialize(mockResponse)).thenReturn("hello"); String actual = toTest.deserialize(mockResponse); assertEquals("hello", actual); }