gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:47:47 24 4
gpt4 key购买 nike

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

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

private static HttpRequestRetryHandler retryHandler() {
return (exception, executionCount, context) -> {
if (executionCount > maxRetries) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return true;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
};
}
}

public CloseableHttpResponse uploadFile(){
CloseableHttpClient httpClient = GetClient.getInstance();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
} catch (Exception ex) {
//handle exception
}
return response;
}

谁能帮我解决这个问题。

最佳答案

你的httpClient有一个“目标”url,比如说localhost:1234。您想要测试的是您的重试代码,因此您不应该触摸 httpClient 本身(因为它不是您的组件,您也不应该需要测试它。)

因此,手头的问题是,当您的 localhost:1234 响应有问题时,您希望看到将运行的重试逻辑(不是您的实现。如果它没有以正确的配置运行,那么它是他们的问题)是否有效。你唯一要做的就是模拟“localhost:1234”!

这个工具http://wiremock.org/是执行此操作的完美选择。您可以为目标网址创建 stub ,并根据您喜欢的几乎任何内容提供一系列响应。

你的代码应该是这样的在调用 uploadFile

之前
    stubFor(post(urlEqualTo("/hash"))
.willReturn(aResponse()
.withStatus(200)
.withBody(externalResponse)));

和调用 uploadFile

并验证步骤来验证到达模拟端点的模拟请求

    Assert.assert* //... whatever you want to assert in your handlers / code / resposnes
verify(postRequestedFor(urlEqualTo("/hash")));

关于java - 如何使用 junit 对 HttpClient 重试逻辑进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57327029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com