模拟Apache HttpClient 4.4 PoolingHttpClientConnectionManager

时间:2015-03-12 14:09:24

标签: java mockito apache-httpclient-4.x

我知道如何模拟default HttpClient,但如何模拟使用Mockito 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

2 个答案:

答案 0 :(得分:1)

模仿HttpRequestExecutorHttpClientConnection更容易。您仍然需要提供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();
}

答案 1 :(得分:1)

刚才意识到PoolingHttpClientConnectionManagerHttpClient使用HttpClients.custom().build()构建的默认连接管理器(至少在v4.4中),所以我回过头来嘲笑{{1} }}

HttpClient

单元测试代码:

protected HttpClient buildHttpClient() {
    return HttpClients.custom()./* other config */.build();
}