在 Mockito 中使用 ResponseHandler 模拟 Apache HTTPClient

Zma*_*aja 5 java mocking mockito apache-httpcomponents

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

String response = httpClient.execute(httpGet, responseHandler);
Run Code Online (Sandbox Code Playgroud)

其中“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 "";
    }
};
Run Code Online (Sandbox Code Playgroud)

有人可以建议我如何做到这一点吗?我想模拟“execute()”方法,但我不想模拟“responseHandler”(我不想测试现有的)。

谢谢!

Ald*_*ldo 2

您可以模拟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));
}
Run Code Online (Sandbox Code Playgroud)