单元测试DefaultHttpRequestRetryHandler [英] Unit testing DefaultHttpRequestRetryHandler

查看:370
本文介绍了单元测试DefaultHttpRequestRetryHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些将文件存储到远程服务器的旧代码.我想使用Apache的DefaultHttpRequestRetryHandler来实现重试逻辑.下面显示了该实现的简化版本.如何测试重试逻辑?

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?

我能够通过重写DefaultHttpRequestRetryHandler类中的retryRequest()来对其进行手动测试,但是一种自动化的方式将是不错的选择. (我正在使用Spock进行测试.)

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

推荐答案

您可能会尝试将 WireMock 与像这样的规则:

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

这篇关于单元测试DefaultHttpRequestRetryHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆