[
https://issues.apache.org/jira/browse/HTTPCLIENT-2183?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17440075#comment-17440075
]
Oleg Kalnichevski commented on HTTPCLIENT-2183:
-----------------------------------------------
[[email protected]] One should never need to mock {{CloseableHttpResponse}}
and {{CloseableHttpClient}}. Those classes are provided largely to facilitate
transition from HC 4.x. One should be using {{ClassicHttpResponse}} and
{{HttpClient}} interfaces in unit tests.
If you absolutely insist I can provide a public factory method for
{{CloseableHttpResponse}} but the enitre class is very likely to get deprecated
in 5.2.
Oleg
> CloseableHttpResponse should not be final to allow mocking
> ----------------------------------------------------------
>
> Key: HTTPCLIENT-2183
> URL: https://issues.apache.org/jira/browse/HTTPCLIENT-2183
> Project: HttpComponents HttpClient
> Issue Type: Improvement
> Components: HttpClient (classic)
> Affects Versions: 5.1.1
> Environment: All
> Reporter: Eric Everman
> Priority: Major
>
> Mocking http responses is a common use case for application code, however,
> its not (easily) possible because
> org.apache.hc.client5.http.impl.classic.CloseableHttpResponse is final.
>
> Example Use Case: I want to test that my application code correctly applies
> my business logic, which is based on the http response code and http response
> content, but I don't want my unit tests to make an actual network connection
> somewhere, so I mock the connection.
>
> However, code like this (a setup method for a JUnit test) will not work
> because CloseableHttpResponse is final:
>
> {code:java}
> CloseableHttpClient httpClient;
> CloseableHttpResponse httpResponse;
> HttpEntity httpEntity;
> protected static final String SIMPLE_CONTENT = "This is *important*";
> @BeforeEach
> public void setup() throws IOException {
> InputStream stream = new
> ByteArrayInputStream(SIMPLE_CONTENT.getBytes(StandardCharsets.UTF_8));
> httpClient = Mockito.mock(CloseableHttpClient.class);
> httpResponse = Mockito.mock(CloseableHttpResponse.class);
> httpEntity = Mockito.mock(HttpEntity.class);
> Mockito.when(httpClient.execute(Mockito.any())).thenReturn(httpResponse);
> Mockito.when(httpResponse.getCode()).thenReturn(200);
> Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
> Mockito.when(httpEntity.getContent()).thenReturn(stream);
> Mockito.when(httpEntity.getContentLength()).thenReturn((long)
> SIMPLE_CONTENT.length());
> }
> {code}
> The code above _would_ have allowed me to inject that http client into my
> application code, then return just exactly what I had scripted for it so I
> can test my code. But, I can't :-/
>
>
--
This message was sent by Atlassian Jira
(v8.20.1#820001)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]