22

我正在尝试构造一个CloseableHttpResponse模拟对象以在我的一个单元测试中返回,但没有构造函数。我找到了这个DefaultHttpResponseFactory,但它只生成一个 HttpResponse。构造 CloseableHttpResponse 的简单方法是什么?我需要调用execute()我的测试然后设置statusLineandentity吗?这似乎是一种奇怪的方法。

这是我试图模拟的方法:

public static CloseableHttpResponse getViaProxy(String url, String ip, int port, String username,
                                                String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(ip, port),
            new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
    try {
        RequestConfig config = RequestConfig.custom()
                .setProxy(new HttpHost(ip, port))
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);

        LOGGER.info("executing request: " + httpGet.getRequestLine() + " via proxy ip: " + ip + " port: " + port +
                " username: " + username + " password: " + password);

        CloseableHttpResponse response = null;
        try {
            return httpclient.execute(httpGet);
        } catch (Exception e) {
            throw new RuntimeException("Could not GET with " + url + " via proxy ip: " + ip + " port: " + port +
                    " username: " + username + " password: " + password, e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                throw new RuntimeException("Could not close response", e);
            }
        }
    } finally {
        try {
            httpclient.close();
        } catch (Exception e) {
            throw new RuntimeException("Could not close httpclient", e);
        }
    }
}

这是使用 PowerMockito 的模拟代码:

    mockStatic(HttpUtils.class);
    when(HttpUtils.getViaProxy("http://www.google.com", anyString(), anyInt(), anyString(), anyString()).thenReturn(/*mockedCloseableHttpResponseObject goes here*/)
4

6 回答 6

36

遵循以下步骤可能会有所帮助:

1.mock它(例如mockito)

CloseableHttpResponse response = mock(CloseableHttpResponse.class);
HttpEntity entity = mock(HttpEntity.class);

2.应用一些规则

when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
when(entity.getContent()).thenReturn(getClass().getClassLoader().getResourceAsStream("result.txt"));
when(response.getEntity()).thenReturn(entity);

3.使用它

when(httpClient.execute((HttpGet) any())).thenReturn(response);
于 2014-01-20T09:17:51.863 回答
4

自从提出这个问题以来已经有一段时间了,但我想提供一个我使用的解决方案。

我创建了一个小类,它扩展了BasicHttpResponse该类并实现了CloseableHttpResponse接口(它只有一个关闭响应的方法)。由于BasicHttpResponse该类包含几乎所有内容的 setter 方法,因此我可以使用以下代码设置所需的所有字段:

public static CloseableHttpResponse buildMockResponse() throws FileNotFoundException {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    String reasonPhrase = "OK";
    StatusLine statusline = new BasicStatusLine(protocolVersion, HttpStatus.SC_OK, reasonPhrase);
    MockCloseableHttpResponse mockResponse = new MockCloseableHttpResponse(statusline);
    BasicHttpEntity entity = new BasicHttpEntity();
    URL url = Thread.currentThread().getContextClassLoader().getResource("response.txt");
    InputStream instream = new FileInputStream(new File(url.getPath()));
    entity.setContent(instream);
    mockResponse.setEntity(entity);
    return mockResponse;
}

我基本上设置了实际代码使用的所有字段。这还包括将文件中的模拟响应内容读取到流中。

于 2015-08-21T14:53:46.507 回答
2

我也想创建一个具体的 CloseableHttpResponse 而不是模拟,所以我在 Apache HTTP 客户端源代码中对其进行了跟踪。

MainClientExec中,执行的所有返回值如下所示:

return new HttpResponseProxy(response, connHolder);

其中 connHolder 可以为空。

HttpResponseProxy只是一个对 connHolder 进行关闭的瘦包装器。不幸的是,它是包保护的,所以它不是(必然)可见的。

我所做的是创建一个“PublicHttpResponseProxy”

package org.apache.http.impl.execchain;

import org.apache.http.HttpResponse;

public class PublicHttpResponseProxy extends HttpResponseProxy {

    public PublicHttpResponseProxy(HttpResponse original) {
        super(original, null);
    }
}

必须在包“org.apache.http.impl.execchain”中(!)基本上将可见性提高到公共并提供带有空连接处理程序的构造函数。

现在我可以实例化一个具体的 CloseableHttpResponse

CloseableHttpResponse response = new PublicHttpResponseProxy(basicResponse);

通常的警告适用。由于代理是包保护的,它不是官方 API 的一部分,所以你可能会在以后不可用的情况下掷骰子。另一方面,它的内容并不多,因此您可以轻松地编写自己的版本。会有一些剪切和粘贴,但不会那么糟糕。

于 2015-01-28T23:13:45.880 回答
1

nvm,我最终只是通过使用来破解它execute()

private CloseableHttpResponse getMockClosesableHttpResponse(HttpResponse response) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse closeableHttpResponse = httpClient.execute(new HttpGet("http://www.test.com"));
    closeableHttpResponse.setEntity(response.getEntity());
    closeableHttpResponse.setStatusLine(response.getStatusLine());
    return closeableHttpResponse;
}
于 2013-11-07T22:26:34.363 回答
1

它很容易创建一个背负现有 BasicHttpResponse 类型的测试实现:

public class TestCloseableHttpResponse extends BasicHttpResponse implements CloseableHttpResponse {

    public TestCloseableHttpResponse(StatusLine statusline, ReasonPhraseCatalog catalog, Locale locale) {
        super(statusline, catalog, locale);
    }

    public TestCloseableHttpResponse(StatusLine statusline) {
        super(statusline);
    }

    public TestCloseableHttpResponse(ProtocolVersion ver, int code, String reason) {
        super(ver, code, reason);
    }


    @Override
    public void close() throws IOException { }

}
于 2020-03-04T20:56:18.910 回答
0

这对我有用:

HttpEntity httpEntity = mock(HttpEntity.class); // mocked

CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class) // mocked

CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient .class) // mocked

String resultJson =
    "{\"key\": \"value\"}";

InputStream is = new ByteArrayInputStream( resultJson.getBytes() );

Mockito.when(httpEntity.getContent()).thenReturn(is);
Mockito.when( httpEntity.getContentLength() ).thenReturn(Long.valueOf(.length()));
StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "success");
Mockito.when(httpEntity.toString()).thenReturn(resultJson);
Mockito.when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
Mockito.when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);

Mockito.when(closeableHttpClient.execute((HttpPost) 
Mockito.any())).thenReturn(closeableHttpResponse);
于 2021-07-06T18:35:52.160 回答