如何创建 CloseableHttpResponse 对象来帮助测试?

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

以下是我试图嘲笑的方法:

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*/)

答案 1

请按照以下步骤操作可能会有所帮助:

1.嘲笑它(例如嘲笑它)

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);

答案 2

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

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

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

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


推荐