TestRestTemplate should not override request factory

Previously `TestRestTemplate` would override the configured
`ClientHttpRequestFactory` if the Apache HTTP client library was on
classpath.

This commit fixes two issues:

1. The existing `ClientHttpRequestFactory` is overridden *only* if it is
using the Apache HTTP client variant, in order to wrap it with the
`TestRestTemplate` custom support

2. Calling `withBasicAuth` will no longer directly use the request
factory returned by the internal `RestTemplate`; if client interceptors
are configured, the request factory is wrapped with an
`InterceptingClientHttpRequestFactory`. If we don't unwrap it,
interceptors are copied/applied twice in the newly created
`TestRestTemplate` instance. For that, we need to use reflection as the
underlying request factory is not accessible directly.

Closes gh-8697
This commit is contained in:
Brian Clozel
2018-02-16 12:21:28 +01:00
parent 7872cda8c1
commit 03a6f97e76
2 changed files with 31 additions and 3 deletions

View File

@@ -37,6 +37,8 @@ import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.http.client.MockClientHttpRequest;
@@ -82,6 +84,15 @@ public class TestRestTemplateTests {
.isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
}
@Test
public void doNotReplaceCustomRequestFactory() {
RestTemplateBuilder builder = new RestTemplateBuilder()
.requestFactory(OkHttp3ClientHttpRequestFactory.class);
TestRestTemplate testRestTemplate = new TestRestTemplate(builder);
assertThat(testRestTemplate.getRestTemplate().getRequestFactory())
.isInstanceOf(OkHttp3ClientHttpRequestFactory.class);
}
@Test
public void getRootUriRootUriSetViaRestTemplateBuilder() {
String rootUri = "http://example.com";
@@ -125,6 +136,7 @@ public class TestRestTemplateTests {
@Test
public void restOperationsAreAvailable() {
RestTemplate delegate = mock(RestTemplate.class);
given(delegate.getRequestFactory()).willReturn(new SimpleClientHttpRequestFactory());
given(delegate.getUriTemplateHandler())
.willReturn(new DefaultUriBuilderFactory());
RestTemplateBuilder builder = mock(RestTemplateBuilder.class);