### Question:
RetryableHttpFetcher { public String fetchAsString(String url) throws ClientProtocolException, IOException { try (CloseableHttpClient client = HttpClientBuilder.create() .setDefaultRequestConfig(MY_REQUEST_CONFIG) .setRetryHandler(MY_HTTP_REQUEST_RETRY_HANDLER) .setServiceUnavailableRetryStrategy(MY_SERVICE_UNAVAILABLE_RETRY_STRATEGY) .build()) { try (CloseableHttpResponse res = client.execute(new HttpGet(url))) { if (res.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(res.getStatusLine().getStatusCode(), res.getStatusLine() .getReasonPhrase()); } return EntityUtils.toString(res.getEntity()); } } }  String fetchAsString(String url);  }### Answer:
@Test public void test1_ok() throws Exception { stubFor(get(urlEqualTo("/hoge.txt")).willReturn( aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withBody("OK"))); String expected = "OK"; String actual = instance.fetchAsString("http: assertThat(actual, is(expected)); }
@Test public void test2_retryAt500() throws Exception { stubFor(get(urlEqualTo("/500")).inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("one time requested") .willReturn(aResponse().withBody("error").withStatus(500))); stubFor(get(urlEqualTo("/500")).inScenario("retry at 500") .whenScenarioStateIs("one time requested") .willReturn(aResponse().withBody("OK").withStatus(200))); String actual = instance.fetchAsString("http: assertThat(actual, is("OK")); }
@Test(expected = HttpResponseException.class) public void test3_retryAt500GiveUp() throws Exception { stubFor(get(urlEqualTo("/500")) .willReturn(aResponse().withBody("500").withStatus(500))); instance.fetchAsString("http: }
@Test public void test4_retryAtTimeout() throws Exception { stubFor(get(urlEqualTo("/timeout")).inScenario("retrying") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("one time requested") .willReturn(aResponse().withBody("error").withStatus(500).withFixedDelay(3000))); stubFor(get(urlEqualTo("/timeout")).inScenario("retrying") .whenScenarioStateIs("one time requested") .willReturn(aResponse().withBody("OK").withStatus(200))); String actual = instance.fetchAsString("http: assertThat(actual, is("OK")); }
@Test(expected = SocketTimeoutException.class) public void test5_retryAtTimeoutGiveUp() throws Exception { stubFor(get(urlEqualTo("/timeout")) .willReturn(aResponse().withBody("timeout").withStatus(500).withFixedDelay(Integer.MAX_VALUE))); instance.fetchAsString("http: }
@Test(expected = HttpResponseException.class) public void notFound() throws Exception { instance.fetchAsString("http: }