【问题标题】:How to properly clean up after using an HttpClient in a unit test在单元测试中使用 HttpClient 后如何正确清理
【发布时间】:2015-02-27 17:19:42
【问题描述】:

在使用 Apache HttpClient 触发请求的单元测试中,我看到了以下设置和清理代码:

private HttpClient httpClient;
private HttpRequestBase httpRequest;


@Before
public void setUp() throws Exception {
    httpClient = new DefaultHttpClient();
}

@After
public void closeRequests() {
    if (httpRequest != null) {
        httpRequest.releaseConnection();
        httpRequest = null;
    }
}

测试比例如发送 get 请求并检查响应:

@Test
public void getSomething() throws Exception {
    httpGet = new HttpGet("http://some/url");
    HttpResponse response = httpclient.execute(httpGet);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_OK));
}

现在我的问题是:这些测试本身是否正确清理?据我了解,releaseConnection() 调用只是将连接交还给客户端的连接管理器,但实际上并没有关闭它。

所以测试不应该这样做:

@After
public void closeConnections() {
    httpClient.getConnectionManager().shutdown();
}

即使没有在 http 请求实例上调用 releaseConnection(),这是否会正确关闭所有连接?

【问题讨论】:

标签: java unit-testing testing apache-httpclient-4.x


【解决方案1】:

是的,你应该这样做。关闭连接管理器(或使用 HC 4.3 和更高版本关闭客户端)是集成测试中正确的做法。

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多