模拟 Apache HttpClient 4.4 PoolingHttpClientConnectionManager

Mocking Apache HttpClient 4.4 PoolingHttpClientConnectionManager

我知道如何用 Mockito 模拟 , but how do I mock the latest (v4.4) HttpClient that is created using a PoolingHttpClientConnectionManager 吗?

我的代码如下所示:

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();
}

刚刚意识到 PoolingHttpClientConnectionManagerHttpClient 使用 HttpClients.custom().build() 构建的默认连接管理器(至少在 v4.4 中),所以我只是回去模拟 HttpClient.

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

单元测试代码:

    @Mock
    HttpClient mockClient;
    @Mock
    HttpResponse mockResponse;
    @Spy
    MyClass myclass = new MyClass();
    . . .
    @Test
    public void myTestCase() {
        . . .
        when(myclass.buildHttpClient()).thenReturn(mockClient);
        when(mockClient.execute(requestCaptor.capture())).thenReturn(mockResponse);
        . . .