gpt4 book ai didi

java - Apache HttpClient 中的单元测试超时

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:08 25 4
gpt4 key购买 nike

我正在尝试测试此方法以检查超时设置是否正确。

public HttpClientBuilder getClientBuilderWithTimeouts(final int connT, final int reqT, final int socketT){
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(connT);
requestBuilder = requestBuilder.setConnectionRequestTimeout(reqT);
requestBuilder = requestBuilder.setSocketTimeout(socketT);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.setDefaultRequestConfig(requestBuilder.build());
return clientBuilder;
}

在我的单元测试中,尽管 getParams() 抛出 UnsupportedOperationException。如何在不使用集成测试的情况下解决这个问题?

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.config.RequestConfig;
...

@Test
public void testGetClientBuilderWithTimeouts(){

HttpClientBuilder clBuilder = utils.getClientBuilderWithTimeouts(10, 20, 30);
CloseableHttpClient testclient = clBuilder.build();

System.out.println(testclient.getParams().getParameter("http.socket.timeout"));
System.out.println(testclient.getParams().getParameter("http.connection.timeout"));
// asserts ..
}

最佳答案

您可以尝试在构建实际客户端之前添加一个 HttpRequestInterceptor,在从您的 utils 类(您想要测试的)获取客户端之后。

...

import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequest;
import org.apache.http.HttpException;

...

builder.addInterceptorFirst(new HttpRequestInterceptor() {

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
// Get hold of the client context, which holds the request config
RequestConfig requestConfig = HttpClientContext.adapt(context).getRequestConfig();

assertEquals(10, requestConfig.getConnectTimeout());
assertEquals(20, requestConfig.getConnectionRequestTimeout());
assertEquals(30, requestConfig.getSocketTimeout());
}
});

现在只需调用任何 URL 并忽略客户端将抛出的异常,以防对 URL 的请求失败。由于拦截器是第一个添加的并且是一个请求拦截器,因此应该在尝试请求之前调用它,为您提供要断言的请求配置。

关于java - Apache HttpClient 中的单元测试超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42145582/

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