Unit test timeouts in Apache HttpClient

妖精的绣舞 提交于 2019-12-12 09:51:06

问题


I'm trying to test this method checking that the timeouts are correctly set.

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

In my unit test though getParams() throws UnsupportedOperationException. How can I solve this without using an integration test?

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:


You can try to add a HttpRequestInterceptor before building the actual client, after getting the client from your utils class (which you want to test).

...

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

Now just do a call to any URL and ignore the exception the client is going to throw in case the request to the URL fails. Since the interceptor is added as first and is a request interceptor, it should be called before the request is attempted, giving you the request config to assert.



来源:https://stackoverflow.com/questions/42145582/unit-test-timeouts-in-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!