2016-09-19 13 views
1

ファイルをリモートサーバに保存する従来のコードを作成しています。 ApacheのDefaultHttpRequestRetryHandlerを使ってリトライロジックを実装したいと思います。実装の簡略化されたバージョンを以下に示します。再試行ロジックをテストするにはどうすればよいですか?ユニットテストDefaultHttpRequestRetryHandler

私は手動でDefaultHttpRequestRetryHandlerクラスのretryRequest()をオーバーライドすることでテストすることができましたが、自動化された方法が良いでしょう。 (私がテストしスポックを使用しています。)

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;  
    } 

答えて

3

おそらくWireMockを使用するように試みることができる、などのルールに:このリンクは質問は将来の訪問者を助ける答える方法についての説明を追加する

@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)) 
} 
+2

。 – JAL