问题
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