Skip to content

Instantly share code, notes, and snippets.

@wookayin
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wookayin/9087154 to your computer and use it in GitHub Desktop.
Save wookayin/9087154 to your computer and use it in GitHub Desktop.
Failing tests for HttpComponentsClientHttpRequestFactory (Spring 4.0.x)
package org.springframework.issues;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.net.SocketTimeoutException;
import org.apache.http.conn.ConnectTimeoutException;
import org.junit.Test;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
// TODO add these tests into HttpComponentsClientHttpRequestFactoryTests.java
public class RestTemplateTest {
@Test(timeout = 3000)
public void connectionTimeoutWorksWell() throws Exception {
HttpClient httpClient = new DefaultHttpClient();
// HttpClient httpClient = HttpClientBuilder.create().build(); // 4.3+ (works OK)
HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(hrf);
int timeout = 1000;
hrf.setConnectTimeout(timeout);
StopWatch sw = new StopWatch();
sw.start();
try {
// 10.255.255.1 is an unroutable address (to yield a connection timeout)
restTemplate.getForObject("http://10.255.255.1:8080", String.class);
}
catch(ResourceAccessException ex) {
Throwable rootEx = ex.getRootCause();
assertThat(rootEx,
anyOf(instanceOf(SocketTimeoutException.class),
instanceOf(ConnectTimeoutException.class) )
);
}
finally {
sw.stop();
}
int elapsedTime = (int) sw.getTotalTimeMillis();
System.out.println(elapsedTime);
assertTrue(String.format("elapsedTime should be about %d ms (was %d ms)", timeout, elapsedTime),
timeout <= elapsedTime && elapsedTime <= timeout + 200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment