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

标签 java mocking mockito apache-commons-httpclient

我正在尝试构建一个 CloseableHttpResponse要在我的单元测试之一中返回的模拟对象,但没有构造函数。我找到了这个 DefaultHttpResponseFactory ,但它只生成一个 HttpResponse。构造 CloseableHttpResponse 的简单方法是什么?我是否需要在测试中调用 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.模拟它(例如 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);

关于java - 如何创建 CloseableHttpResponse 对象来帮助测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846526/

相关文章:

java - 使用 jdbc4 连接到数据库引擎的通用代码?

c# - 将模拟概念应用于现实生活中的单元测试时大脑卡住

java - 模拟函数在指定 return 后返回 null

java - @Mock、@MockBean 和 Mockito.mock() 之间的区别

java - 导出项目文件夹中图像的位置

java - 从 TimeStamp 获取月份和日期

java - Web 服务抛出 ClassNotFoundException

php - 如何使用 PHPUnit 测试和模拟 zend 框架 Controller ?

amazon-web-services - 模拟 AWS Promise 时出现 "docClient.scan(...).promise is not a function"错误

java - 确保在 mockito 中不调用非模拟方法