gpt4 book ai didi

java - 模拟 Apache HttpClient 4.4 PoolingHttpClientConnectionManager

转载 作者:行者123 更新时间:2023-12-02 04:53:26 26 4
gpt4 key购买 nike

我知道如何模拟 default HttpClient ,但是我如何模拟使用 PoolingHttpClientConnectionManager 创建的最新(v4.4)HttpClient与莫基托?

我的代码如下所示:

PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
...
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(mgr).build();
HttpResponse response = httpClient.execute(request);
... // here I want to substitute a mocked HttpResponse

最佳答案

模拟 HttpRequestExecutor 可能比模拟 HttpClientConnection 更容易。您仍然需要提供 HttpClientConnectionManager 的无操作实现,以防止 HttpClient 创建和连接套接字

HttpRequestExecutor requestExecutor = Mockito.mock(HttpRequestExecutor.class);
Mockito.when(requestExecutor.execute(
Mockito.<HttpRequest>any(),
Mockito.<HttpClientConnection>any(),
Mockito.<HttpContext>any())).thenReturn(new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "Hah"));

HttpClientConnectionManager cm = Mockito.mock(HttpClientConnectionManager.class);
HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
ConnectionRequest connRequest = Mockito.mock(ConnectionRequest.class);
Mockito.when(cm.requestConnection(
Mockito.<HttpRoute>any(),
Mockito.any())).thenReturn(connRequest);
Mockito.when(connRequest.get(
Mockito.anyLong(),
Mockito.<TimeUnit>any())).thenReturn(conn);

CloseableHttpClient client = HttpClients.custom()
.setRequestExecutor(requestExecutor)
.setConnectionManager(cm)
.build();

CloseableHttpResponse response = client.execute(new HttpGet("http://pampa/"));
try {
System.out.println(response.getStatusLine());
} finally {
response.close();
}

关于java - 模拟 Apache HttpClient 4.4 PoolingHttpClientConnectionManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012024/

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