单元测试 DefaultHttpRequestRetryHandler [英] Unit testing DefaultHttpRequestRetryHandler

查看:20
本文介绍了单元测试 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天全站免登陆