我一直在尝试使用ResponseHandler模​​拟Apache HTTPClient,以便使用Mockito测试我的服务。有问题的方法是:

String response = httpClient.execute(httpGet, responseHandler);

其中“responseHandler”是一个ResponseHandler:
ResponseHandler<String> responseHandler = response -> {
    int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_OK) {
        return EntityUtils.toString(response.getEntity());
    } else {
        log.error("Accessing API returned error code: {}, reason: {}", status, response.getStatusLine().getReasonPhrase());
        return "";
    }
};

有人可以建议我该怎么做吗?我想模拟“execute()”方法,但是我不想模拟“responseHandler”(我不想测试现有的)。

谢谢!

最佳答案

您可以模拟HttpClient并使用Mockito的thenAnswer()方法。例如,类似:

@Test
public void http_ok() throws IOException {
    String expectedContent = "expected";

    HttpClient httpClient = mock(HttpClient.class);
    when(httpClient.execute(any(HttpUriRequest.class), eq(responseHandler)))
            .thenAnswer((InvocationOnMock invocation) -> {
                BasicHttpResponse ret = new BasicHttpResponse(
                        new BasicStatusLine(HttpVersion.HTTP_1_1, HttpURLConnection.HTTP_OK, "OK"));
                ret.setEntity(new StringEntity(expectedContent, StandardCharsets.UTF_8));

                @SuppressWarnings("unchecked")
                ResponseHandler<String> handler
                        = (ResponseHandler<String>) invocation.getArguments()[1];
                return handler.handleResponse(ret);
            });

    String result = httpClient.execute(new HttpGet(), responseHandler);

    assertThat(result, is(expectedContent));
}

10-02 02:48