Apache HttpClient中的单元测试超时

时间:2017-02-09 19:48:42

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

我试图测试此方法,检查超时是否正确设置。

public HttpClientBuilder getClientBuilderWithTimeouts(final int connT, final int reqT, final int socketT){
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(connT);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(reqT);
    requestBuilder = requestBuilder.setSocketTimeout(socketT);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();     
    clientBuilder.setDefaultRequestConfig(requestBuilder.build());
    return clientBuilder;
}

在我的单元测试中getParams()抛出UnsupportedOperationException。如何在不使用集成测试的情况下解决这个问题?

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.config.RequestConfig;
...

@Test
public void testGetClientBuilderWithTimeouts(){

    HttpClientBuilder clBuilder = utils.getClientBuilderWithTimeouts(10, 20, 30);
    CloseableHttpClient testclient = clBuilder.build();

    System.out.println(testclient.getParams().getParameter("http.socket.timeout"));
    System.out.println(testclient.getParams().getParameter("http.connection.timeout"));
    // asserts ..
}

1 个答案:

答案 0 :(得分:3)

在从utils类(您要测试的)获取客户端之后,可以尝试在构建实际客户端之前添加HttpRequestInterceptor

...

import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequest;
import org.apache.http.HttpException;

... 

builder.addInterceptorFirst(new HttpRequestInterceptor() {

      @Override
      public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        // Get hold of the client context, which holds the request config
        RequestConfig requestConfig = HttpClientContext.adapt(context).getRequestConfig();

        assertEquals(10, requestConfig.getConnectTimeout());
        assertEquals(20, requestConfig.getConnectionRequestTimeout());
        assertEquals(30, requestConfig.getSocketTimeout());
      }
    });     

现在只需调用任何URL,并忽略客户端将要抛出的异常,以防对URL的请求失败。由于拦截器是作为第一个添加的并且是请求拦截器,因此应该在尝试请求之前调用它,从而为请求配置断言。