Unit testing DefaultHttpRequestRetryHandler

拥有回忆 提交于 2019-12-24 06:03:36

问题


I'm working on some legacy code that stores files to a remote server. I'd like to use Apache's DefaultHttpRequestRetryHandler to implement a retry logic. A simplified version of the implementation is shown below. How do I test my retry logic?

I was able to manually test it by overriding retryRequest() in the DefaultHttpRequestRetryHandler class but an automated way would be nice. (I'm using Spock to test.)

   private CloseableHttpClient getHttpClient() {
        DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler();
        CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(retryHandler).build();
        return httpClient;
   }

   public CloseableHttpResponse uploadFile(){    
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post, getHttpContext());
        } catch (Exception ex) {
            //handle exception
        }
        return response;    
   }

回答1:


You could probably try to use WireMock, with a rule like:

@Rule
public WireMockRule wireMockRule = new WireMockRule(8080);

@Test
public void testRetry()
  throws Exception {
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/retry"))
                    .inScenario("retry")
                    .whenScenarioStateIs(Scenario.STARTED)
                    .willSetStateTo("first try").willReturn(aResponse().withBody("error").withStatus(500)));
    WireMock.stubFor(
            WireMock.get(WireMock.urlEqualTo("/retry"))
                    .inScenario("retry")
                    .whenScenarioStateIs(Scenario.STARTED)
                    .willSetStateTo("first try").willReturn(aResponse().withBody("OK").withStatus(200)));
    Integer responseCode = new TestClass().getHttpClient().execute(new HttpHost("localhost", 8080), new HttpGet("http://localhost:8080/retry")).getStatusLine().getStatusCode();
    assertThat(responseCode, is(200))
}


来源:https://stackoverflow.com/questions/39579202/unit-testing-defaulthttprequestretryhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!