问题
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