如何使用 junit 对 HttpClient 重试逻辑进行单元测试

我正在使用 apache http 客户端来使用服务,我需要根据超时和响应代码重试请求。为此,我实现了如下代码。如何为超时和响应代码场景的重试逻辑编写 junit 测试。我想以这种方式编写单元测试,当我发送任何 post/get 请求时,如果它返回 429 错误代码响应或任何 TimeOutException 我应该确保重试逻辑正确执行。我不知道如何为重试逻辑编写单元测试。通过谷歌搜索,我找到了以下链接,但它对我没有帮助。

单元测试 DefaultHttpRequestRetryHandler

我正在使用 junit、Mockito 编写单元测试和 PowerMock 来模拟静态方法。

public class GetClient {


private static CloseableHttpClient httpclient;


public static CloseableHttpClient getInstance() {


        try {

            HttpClientBuilder builder = HttpClients.custom().setMaxConnTotal(3)

                    .setMaxConnPerRoute(3);

            builder.setRetryHandler(retryHandler());

            builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

            int waitPeriod = 200;


            @Override

            public boolean retryRequest(final HttpResponse response, final int executionCount,

                final HttpContext context) {


                int statusCode = response.getStatusLine().getStatusCode();

                return (((statusCode == 429) || (statusCode >= 300 && statusCode <= 399))

                            && (executionCount < 3));

            }


            @Override

            public long getRetryInterval() {

                return waitPeriod;

            }

            });            


            httpclient = builder.build();


        } catch (Exception e) {

            //handle exception

        }

        return httpclient;

    }

天涯尽头无女友
浏览 115回答 1
1回答

临摹微笑

您的 httpClient 有一个“目标”网址,可以说是 localhost:1234。你想要测试的是你的重试代码,所以你不应该触摸 httpClient 本身(因为它不是你的组件,你不应该也需要测试它。)因此,手头的问题是当您的 localhost:1234 响应有问题时,您希望看到将运行的重试逻辑(不是您的实现..如果它没有以正确的 conf 运行是他们的问题)有效..唯一的事情你所要做的就是模拟“localhost:1234”!这个工具http://wiremock.org/是执行此操作的完美选择。您可以为您的目标 url 创建存根,并根据您喜欢的几乎任何内容给出一系列响应。您的代码在调用之前应该看起来像uploadFile&nbsp; &nbsp; stubFor(post(urlEqualTo("/hash"))&nbsp; &nbsp; &nbsp; &nbsp; .willReturn(aResponse()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withStatus(200)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .withBody(externalResponse)));打电话后uploadFile并验证步骤以验证到达模拟端点的模拟请求&nbsp; &nbsp; Assert.assert* //... whatever you want to assert in your handlers / code / resposnes&nbsp; &nbsp; verify(postRequestedFor(urlEqualTo("/hash")));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java