在Mockito中使用ResponseHandler模​​拟Apache HTTPClient

时间:2018-04-05 11:48:58

标签: java mocking mockito apache-httpcomponents

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

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

where" 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 "";
    }
};

有人可以建议我怎么做到这一点?我想模仿&#34;执行()&#34;方法,但我不想嘲笑&#34; responseHandler&#34; (我不想测试现有的那个)。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以模拟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));
}