CachingHttpClient { public synchronized T get(URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null"); } Optional<byte[]> content = Optional.empty(); try { content = cache.get(url, () -> Optional.of(getContent(url))); } catch (ExecutionException e) { cache.put(url, Optional.empty()); throw new IOException("Unable to get " + url.toString(), e.getCause()); } return content.isPresent() ? callback.transform(content.get()) : null; } CachingHttpClient(ContentReceviedCallback<T> callback); synchronized T get(URL url);  }
@Test public void testMultipleUnsuccessfulRequests() throws Exception { URL unreachableURL = getUniqueURL(PATH_TO_MISSING_RESOURCE); try { testClient.get(unreachableURL); } catch (IOException e) { assertThat(e, instanceOf(IOException.class)); assertThat(e.getMessage(), equalTo("Unable to get " + unreachableURL.toString())); assertThat(e.getCause(), instanceOf(FileNotFoundException.class)); } assertNull(testClient.get(unreachableURL)); assertNull(testClient.get(unreachableURL)); verify(server.getHandler(), times(1)).handle(any(), any(), any(), any()); }
@Test public void testMultipleSuccessfulRequests() throws Exception { URL reachableURL = getUniqueURL(PATH_TO_RESOURCE); assertNotNull(testClient.get(reachableURL)); assertNotNull(testClient.get(reachableURL)); assertNotNull(testClient.get(reachableURL)); verify(server.getHandler(), times(1)).handle(any(), any(), any(), any()); }
@Test public void testSuccessAndFailure() throws Exception { URL url = getUniqueURL(PATH_TO_RESOURCE); assertNotNull(testClient.get(url)); Mockito.doNothing().when(server.getHandler()).handle(any(), any(), any(), any()); assertNotNull(testClient.get(url)); verify(server.getHandler(), times(1)).handle(any(), any(), any(), any()); }
@Test public void testFailureAndSuccess() throws Exception { URL url = getUniqueURL(PATH_TO_RESOURCE); Mockito.doNothing().when(server.getHandler()).handle(any(), any(), any(), any()); try { testClient.get(url); } catch (IOException e) { assertThat(e, instanceOf(IOException.class)); assertThat(e.getMessage(), equalTo("Unable to get " + url.toString())); assertThat(e.getCause(), instanceOf(FileNotFoundException.class)); } mockHandler(server.getHandler()); assertNull(testClient.get(url)); assertNull(testClient.get(url)); verify(server.getHandler(), times(1)).handle(any(), any(), any(), any()); }