Make TestRestTemplate not extend RestTemplate

Update TestRestTemplate so that it no longer directly extends
RestTemplate. Prior to this commit it was possible that TestRestTemplate
could interfere with user defined RestTemplate beans.

TestRestTemplate offers the same methods as RestTemplate so should be
a drop-in replacement. If access is needed to the actual underlying
template the `getRestTemplate()` method should be used.

Fixes gh-5915
pull/5980/head
Phillip Webb 9 years ago
parent 1947b92481
commit bcfa2e6676

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationCustomFilterContextPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationCustomFilterPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationCustomObjectMapperProviderTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationCustomServletContextPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationCustomServletPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationDefaultFilterPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationDefaultServletPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationObjectMapperProviderTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JerseyAutoConfigurationWithoutApplicationPathTests {
@Autowired
private RestTemplate restTemplate;
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {

@ -94,7 +94,6 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -327,7 +326,7 @@ public class OAuth2AutoConfigurationTests {
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
String baseUrl = "http://localhost:"
+ this.context.getEmbeddedServletContainer().getPort();
RestTemplate rest = new TestRestTemplate();
TestRestTemplate rest = new TestRestTemplate();
// First, verify the web endpoint can't be reached
assertEndpointUnauthorized(baseUrl, rest);
// Since we can't reach it, need to collect an authorization token
@ -371,7 +370,7 @@ public class OAuth2AutoConfigurationTests {
return body;
}
private void assertEndpointUnauthorized(String baseUrl, RestTemplate rest) {
private void assertEndpointUnauthorized(String baseUrl, TestRestTemplate rest) {
URI uri = URI.create(baseUrl + "/secured");
ResponseEntity<String> entity = rest
.exchange(new RequestEntity<Void>(HttpMethod.GET, uri), String.class);

@ -34,7 +34,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -51,7 +50,7 @@ public class RemappedErrorViewIntegrationTests {
@LocalServerPort
private int port;
private RestTemplate template = new TestRestTemplate();
private TestRestTemplate template = new TestRestTemplate();
@Test
public void directAccessToErrorPage() throws Exception {

@ -26,7 +26,6 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -37,7 +36,7 @@ public class SampleJerseyApplicationTests {
@LocalServerPort
private int port;
private RestTemplate restTemplate = new TestRestTemplate();
private TestRestTemplate restTemplate = new TestRestTemplate();
@Test
public void contextLoads() {

@ -16,11 +16,6 @@
package sample.jetty.ssl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@ -51,16 +46,7 @@ public class SampleJettySslApplicationTests {
@Test
public void testHome() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
.build();
TestRestTemplate testRestTemplate = new TestRestTemplate();
((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory())
.setHttpClient(httpClient);
TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL);
ResponseEntity<String> entity = testRestTemplate
.getForEntity("https://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -67,7 +66,7 @@ public class SampleJettyApplicationTests {
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new TestRestTemplate();
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<byte[]> entity = restTemplate.exchange(
"http://localhost:" + this.port, HttpMethod.GET, requestEntity,

@ -16,11 +16,6 @@
package sample.jetty8.ssl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@ -51,16 +46,7 @@ public class SampleJetty8SslApplicationTests {
@Test
public void testHome() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
.build();
TestRestTemplate testRestTemplate = new TestRestTemplate();
((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory())
.setHttpClient(httpClient);
TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL);
ResponseEntity<String> entity = testRestTemplate
.getForEntity("https://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -66,7 +65,7 @@ public class SampleJetty8ApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new TestRestTemplate();
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<byte[]> entity = restTemplate.exchange(
"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
byte[].class);

@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -66,7 +65,7 @@ public class SampleJetty93ApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new TestRestTemplate();
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<byte[]> entity = restTemplate.exchange(
"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
byte[].class);

@ -16,11 +16,6 @@
package sample.tomcat.ssl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@ -46,16 +41,7 @@ public class SampleTomcatSslApplicationTests {
@Test
public void testHome() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
.build();
TestRestTemplate testRestTemplate = new TestRestTemplate();
((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory())
.setHttpClient(httpClient);
TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL);
ResponseEntity<String> entity = testRestTemplate
.getForEntity("https://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -66,7 +65,7 @@ public class SampleTomcatApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new TestRestTemplate();
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<byte[]> entity = restTemplate.exchange(
"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
byte[].class);

@ -16,11 +16,6 @@
package sample.undertow.ssl;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
@ -51,16 +46,7 @@ public class SampleUndertowSslApplicationTests {
@Test
public void testHome() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
.build();
TestRestTemplate testRestTemplate = new TestRestTemplate();
((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory())
.setHttpClient(httpClient);
TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL);
ResponseEntity<String> entity = testRestTemplate
.getForEntity("https://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);

@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@ -68,7 +67,7 @@ public class SampleUndertowApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new TestRestTemplate();
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<byte[]> entity = restTemplate.exchange(
"http://localhost:" + this.port, HttpMethod.GET, requestEntity,
byte[].class);

@ -16,6 +16,31 @@
package org.springframework.boot.test;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.util.Base64Utils;
import org.springframework.util.ClassUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
/**
@ -30,15 +55,16 @@ import org.springframework.web.client.RestTemplate;
* {@link org.springframework.boot.test.web.client.TestRestTemplate}
*/
@Deprecated
public class TestRestTemplate
extends org.springframework.boot.test.web.client.TestRestTemplate {
public class TestRestTemplate extends RestTemplate {
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Create a new {@link TestRestTemplate} instance.
* @param httpClientOptions client options to use if the Apache HTTP Client is used
*/
public TestRestTemplate(HttpClientOption... httpClientOptions) {
super(convertOptions(httpClientOptions));
this(null, null, httpClientOptions);
}
/**
@ -49,18 +75,28 @@ public class TestRestTemplate
*/
public TestRestTemplate(String username, String password,
HttpClientOption... httpClientOptions) {
super(username, password, convertOptions(httpClientOptions));
if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
setRequestFactory(
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
}
addAuthentication(username, password);
setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
}
private static org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[] convertOptions(
HttpClientOption[] options) {
org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[] result = new org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[options.length];
for (int i = 0; i < options.length; i++) {
HttpClientOption option = options[i];
result[i] = org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption
.valueOf(option.name());
private void addAuthentication(String username, String password) {
if (username == null) {
return;
}
return result;
List<ClientHttpRequestInterceptor> interceptors = Collections
.<ClientHttpRequestInterceptor>singletonList(
new BasicAuthorizationInterceptor(username, password));
setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
interceptors));
}
/**
@ -80,4 +116,62 @@ public class TestRestTemplate
}
private static class BasicAuthorizationInterceptor
implements ClientHttpRequestInterceptor {
private final String username;
private final String password;
BasicAuthorizationInterceptor(String username, String password) {
this.username = username;
this.password = (password == null ? "" : password);
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
String token = Base64Utils.encodeToString(
(this.username + ":" + this.password).getBytes(UTF_8));
request.getHeaders().add("Authorization", "Basic " + token);
return execution.execute(request, body);
}
}
/**
* {@link HttpComponentsClientHttpRequestFactory} to apply customizations.
*/
protected static class CustomHttpComponentsClientHttpRequestFactory
extends HttpComponentsClientHttpRequestFactory {
private final String cookieSpec;
private final boolean enableRedirects;
public CustomHttpComponentsClientHttpRequestFactory(
HttpClientOption[] httpClientOptions) {
Set<HttpClientOption> options = new HashSet<TestRestTemplate.HttpClientOption>(
Arrays.asList(httpClientOptions));
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES)
? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES);
this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS);
}
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(getRequestConfig());
return context;
}
protected RequestConfig getRequestConfig() {
Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec)
.setAuthenticationEnabled(false)
.setRedirectsEnabled(this.enableRedirects);
return builder.build();
}
}
}

@ -23,7 +23,6 @@ import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.web.client.RestTemplate;
/**
* {@link ContextCustomizer} for {@link SpringBootTest}.
@ -39,7 +38,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer {
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(
mergedContextConfiguration.getTestClass(), SpringBootTest.class);
if (annotation.webEnvironment().isEmbedded()) {
RestTemplate restTemplate = TestRestTemplateFactory
Object restTemplate = TestRestTemplateFactory
.createRestTemplate(context.getEnvironment());
context.getBeanFactory().registerSingleton("testRestTemplate", restTemplate);
}

@ -23,40 +23,63 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.ClassUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriTemplateHandler;
import org.springframework.web.util.UriTemplateHandler;
/**
* Convenient subclass of {@link RestTemplate} that is suitable for integration tests.
* Convenient alternative of {@link RestTemplate} that is suitable for integration tests.
* They are fault tolerant, and optionally can carry Basic authentication headers. If
* Apache Http Client 4.3.2 or better is available (recommended) it will be used as the
* client, and by default configured to ignore cookies and redirects.
* <p>
* Note: To prevent injection problems this class internationally does not extend
* {@link RestTemplate}. If you need access to the underlying {@link RestTemplate} use
* {@link #getRestTemplate()}.
*
* @author Dave Syer
* @author Phillip Webb
* @since 1.4.0
*/
public class TestRestTemplate extends RestTemplate {
public class TestRestTemplate {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final RestTemplate restTemplate;
/**
* Create a new {@link TestRestTemplate} instance.
* @param httpClientOptions client options to use if the Apache HTTP Client is used
@ -73,28 +96,798 @@ public class TestRestTemplate extends RestTemplate {
*/
public TestRestTemplate(String username, String password,
HttpClientOption... httpClientOptions) {
this.restTemplate = createRestTemplate(username, password, httpClientOptions);
}
/**
* Factory method used to create the underlying {@link RestTemplate}.
* @param username the username to use (or {@code null})
* @param password the password (or {@code null})
* @param httpClientOptions client options to use if the Apache HTTP Client is used
* @return the delegate {@link RestTemplate}
*/
protected RestTemplate createRestTemplate(String username, String password,
HttpClientOption... httpClientOptions) {
RestTemplate restTemplate = new RestTemplate();
if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
setRequestFactory(
restTemplate.setRequestFactory(
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
}
addAuthentication(username, password);
setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
addAuthentication(restTemplate, username, password);
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
return restTemplate;
}
public TestRestTemplate(RestTemplate restTemplate) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
this.restTemplate = restTemplate;
}
private void addAuthentication(String username, String password) {
private void addAuthentication(RestTemplate restTemplate, String username,
String password) {
if (username == null) {
return;
}
List<ClientHttpRequestInterceptor> interceptors = Collections
.<ClientHttpRequestInterceptor>singletonList(
new BasicAuthorizationInterceptor(username, password));
setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
interceptors));
restTemplate.setRequestFactory(new InterceptingClientHttpRequestFactory(
restTemplate.getRequestFactory(), interceptors));
}
/**
* Configure the {@link UriTemplateHandler} to use to expand URI templates. By default
* the {@link DefaultUriTemplateHandler} is used which relies on Spring's URI template
* support and exposes several useful properties that customize its behavior for
* encoding and for prepending a common base URL. An alternative implementation may be
* used to plug an external URI template library.
* @param handler the URI template handler to use
*/
public void setUriTemplateHandler(UriTemplateHandler handler) {
this.restTemplate.setUriTemplateHandler(handler);
}
/**
* Retrieve a representation by doing a GET on the specified URL. The response (if
* any) is converted and returned.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param responseType the type of the return value
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error on-client side HTTP error
* @see RestTemplate#getForObject(String, Class, Object...)
*/
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables)
throws RestClientException {
return this.restTemplate.getForObject(url, responseType, urlVariables);
}
/**
* Retrieve a representation by doing a GET on the URI template. The response (if any)
* is converted and returned.
* <p>
* URI Template variables are expanded using the given map.
* @param url the URL
* @param responseType the type of the return value
* @param urlVariables the map containing variables for the URI template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#getForObject(String, Class, Object...)
*/
public <T> T getForObject(String url, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.getForObject(url, responseType, urlVariables);
}
/**
* Retrieve a representation by doing a GET on the URL . The response (if any) is
* converted and returned.
* @param url the URL
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#getForObject(java.net.URI, java.lang.Class)
*/
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
return this.restTemplate.getForObject(url, responseType);
}
/**
* Retrieve an entity by doing a GET on the specified URL. The response is converted
* and stored in an {@link ResponseEntity}.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param responseType the type of the return value
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class,
* java.lang.Object[])
*/
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
Object... urlVariables) throws RestClientException {
return this.restTemplate.getForEntity(url, responseType, urlVariables);
}
/**
* Retrieve a representation by doing a GET on the URI template. The response is
* converted and stored in an {@link ResponseEntity}.
* <p>
* URI Template variables are expanded using the given map.
* @param url the URL
* @param responseType the type of the return value
* @param urlVariables the map containing variables for the URI template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.getForEntity(url, responseType, urlVariables);
}
/**
* Retrieve a representation by doing a GET on the URL . The response is converted and
* stored in an {@link ResponseEntity}.
* @param url the URL
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#getForEntity(java.net.URI, java.lang.Class)
*/
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType)
throws RestClientException {
return this.restTemplate.getForEntity(url, responseType);
}
/**
* Retrieve all headers of the resource specified by the URI template.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param urlVariables the variables to expand the template
* @return all HTTP headers of that resource
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[])
*/
public HttpHeaders headForHeaders(String url, Object... urlVariables)
throws RestClientException {
return this.restTemplate.headForHeaders(url, urlVariables);
}
/**
* Retrieve all headers of the resource specified by the URI template.
* <p>
* URI Template variables are expanded using the given map.
* @param url the URL
* @param urlVariables the map containing variables for the URI template
* @return all HTTP headers of that resource
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#headForHeaders(java.lang.String, java.util.Map)
*/
public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.headForHeaders(url, urlVariables);
}
/**
* Retrieve all headers of the resource specified by the URL.
* @param url the URL
* @return all HTTP headers of that resource
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#headForHeaders(java.net.URI)
*/
public HttpHeaders headForHeaders(URI url) throws RestClientException {
return this.restTemplate.headForHeaders(url);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the value of the {@code Location} header. This header typically indicates where the
* new resource is stored.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param urlVariables the variables to expand the template
* @return the value for the {@code Location} header
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
* java.lang.Object[])
*/
public URI postForLocation(String url, Object request, Object... urlVariables)
throws RestClientException {
return this.restTemplate.postForLocation(url, request, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the value of the {@code Location} header. This header typically indicates where the
* new resource is stored.
* <p>
* URI Template variables are expanded using the given map.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param urlVariables the variables to expand the template
* @return the value for the {@code Location} header
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
* java.util.Map)
*/
public URI postForLocation(String url, Object request, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.postForLocation(url, request, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URL, and returns the value
* of the {@code Location} header. This header typically indicates where the new
* resource is stored.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @return the value for the {@code Location} header
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForLocation(java.net.URI, java.lang.Object)
*/
public URI postForLocation(URI url, Object request) throws RestClientException {
return this.restTemplate.postForLocation(url, request);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the representation found in the response.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
* java.lang.Class, java.lang.Object[])
*/
public <T> T postForObject(String url, Object request, Class<T> responseType,
Object... urlVariables) throws RestClientException {
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the representation found in the response.
* <p>
* URI Template variables are expanded using the given map.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
public <T> T postForObject(String url, Object request, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URL, and returns the
* representation found in the response.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class)
*/
public <T> T postForObject(URI url, Object request, Class<T> responseType)
throws RestClientException {
return this.restTemplate.postForObject(url, request, responseType);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the response as {@link ResponseEntity}.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the response type to return
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
* java.lang.Class, java.lang.Object[])
*/
public <T> ResponseEntity<T> postForEntity(String url, Object request,
Class<T> responseType, Object... urlVariables) throws RestClientException {
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URI template, and returns
* the response as {@link HttpEntity}.
* <p>
* URI Template variables are expanded using the given map.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the response type to return
* @param urlVariables the variables to expand the template
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> postForEntity(String url, Object request,
Class<T> responseType, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
}
/**
* Create a new resource by POSTing the given object to the URL, and returns the
* response as {@link ResponseEntity}.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed, may be {@code null}
* @param responseType the response type to return
* @param <T> the type of the return value
* @return the converted object
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class)
*/
public <T> ResponseEntity<T> postForEntity(URI url, Object request,
Class<T> responseType) throws RestClientException {
return this.restTemplate.postForEntity(url, request, responseType);
}
/**
* Create or update a resource by PUTting the given object to the URI.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be PUT, may be {@code null}
* @param urlVariables the variables to expand the template
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[])
*/
public void put(String url, Object request, Object... urlVariables)
throws RestClientException {
this.restTemplate.put(url, request, urlVariables);
}
/**
* Creates a new resource by PUTting the given object to URI template.
* <p>
* URI Template variables are expanded using the given map.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be PUT, may be {@code null}
* @param urlVariables the variables to expand the template
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map)
*/
public void put(String url, Object request, Map<String, ?> urlVariables)
throws RestClientException {
this.restTemplate.put(url, request, urlVariables);
}
/**
* Creates a new resource by PUTting the given object to URL.
* <p>
* The {@code request} parameter can be a {@link HttpEntity} in order to add
* additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be PUT, may be {@code null}
* @throws RestClientException on-client side HTTP error
* @see HttpEntity
* @see RestTemplate#put(java.net.URI, java.lang.Object)
*/
public void put(URI url, Object request) throws RestClientException {
this.restTemplate.put(url, request);
}
/**
* Delete the resources at the specified URI.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param urlVariables the variables to expand in the template
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#delete(java.lang.String, java.lang.Object[])
*/
public void delete(String url, Object... urlVariables) throws RestClientException {
this.restTemplate.delete(url, urlVariables);
}
/**
* Delete the resources at the specified URI.
* <p>
* URI Template variables are expanded using the given map.
* @param url the URL
* @param urlVariables the variables to expand the template
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#delete(java.lang.String, java.util.Map)
*/
public void delete(String url, Map<String, ?> urlVariables)
throws RestClientException {
this.restTemplate.delete(url, urlVariables);
}
/**
* Delete the resources at the specified URL.
* @param url the URL
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#delete(java.net.URI)
*/
public void delete(URI url) throws RestClientException {
this.restTemplate.delete(url);
}
/**
* Return the value of the Allow header for the given URI.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param urlVariables the variables to expand in the template
* @return the value of the allow header
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[])
*/
public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables)
throws RestClientException {
return this.restTemplate.optionsForAllow(url, urlVariables);
}
/**
* Return the value of the Allow header for the given URI.
* <p>
* URI Template variables are expanded using the given map.
* @param url the URL
* @param urlVariables the variables to expand in the template
* @return the value of the allow header
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map)
*/
public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.optionsForAllow(url, urlVariables);
}
/**
* Return the value of the Allow header for the given URL.
* @param url the URL
* @return the value of the allow header
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#optionsForAllow(java.net.URI)
*/
public Set<HttpMethod> optionsForAllow(URI url) throws RestClientException {
return this.restTemplate.optionsForAllow(url);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[])
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType, Object... urlVariables)
throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class)
*/
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}. The given
* {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference, java.lang.Object[])
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Object... urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}. The given
* {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference, java.util.Map)
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity
* to the request, and returns the response as {@link ResponseEntity}. The given
* {@link ParameterizedTypeReference} is used to pass generic type information:
* <pre class="code">
* ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = template.exchange(&quot;http://example.com&quot;,HttpMethod.GET, null, myBean);
* </pre>
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestEntity the entity (headers and/or body) to write to the request, may
* be {@code null}
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference)
*/
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType);
}
/**
* Execute the request specified in the given {@link RequestEntity} and return the
* response as {@link ResponseEntity}. Typically used in combination with the static
* builder methods on {@code RequestEntity}, for instance: <pre class="code">
* MyRequest body = ...
* RequestEntity request = RequestEntity.post(new URI(&quot;http://example.com/foo&quot;)).accept(MediaType.APPLICATION_JSON).body(body);
* ResponseEntity&lt;MyResponse&gt; response = template.exchange(request, MyResponse.class);
* </pre>
* @param requestEntity the entity to write to the request
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class)
*/
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
Class<T> responseType) throws RestClientException {
return this.restTemplate.exchange(requestEntity, responseType);
}
/**
* Execute the request specified in the given {@link RequestEntity} and return the
* response as {@link ResponseEntity}. The given {@link ParameterizedTypeReference} is
* used to pass generic type information: <pre class="code">
* MyRequest body = ...
* RequestEntity request = RequestEntity.post(new URI(&quot;http://example.com/foo&quot;)).accept(MediaType.APPLICATION_JSON).body(body);
* ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyResponse&gt;&gt;() {};
* ResponseEntity&lt;List&lt;MyResponse&gt;&gt; response = template.exchange(request, myBean);
* </pre>
* @param requestEntity the entity to write to the request
* @param responseType the type of the return value
* @param <T> the type of the return value
* @return the response as entity
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#exchange(org.springframework.http.RequestEntity,
* org.springframework.core.ParameterizedTypeReference)
*/
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException {
return this.restTemplate.exchange(requestEntity, responseType);
}
/**
* Execute the HTTP method to the given URI template, preparing the request with the
* {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}.
* <p>
* URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestCallback object that prepares the request
* @param responseExtractor object that extracts the return value from the response
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return an arbitrary object, as returned by the {@link ResponseExtractor}
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.web.client.RequestCallback,
* org.springframework.web.client.ResponseExtractor, java.lang.Object[])
*/
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Object... urlVariables)
throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
urlVariables);
}
/**
* Execute the HTTP method to the given URI template, preparing the request with the
* {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}.
* <p>
* URI Template variables are expanded using the given URI variables map.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestCallback object that prepares the request
* @param responseExtractor object that extracts the return value from the response
* @param urlVariables the variables to expand in the template
* @param <T> the type of the return value
* @return an arbitrary object, as returned by the {@link ResponseExtractor}
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.web.client.RequestCallback,
* org.springframework.web.client.ResponseExtractor, java.util.Map)
*/
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
urlVariables);
}
/**
* Execute the HTTP method to the given URL, preparing the request with the
* {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}.
* @param url the URL
* @param method the HTTP method (GET, POST, etc)
* @param requestCallback object that prepares the request
* @param responseExtractor object that extracts the return value from the response
* @param <T> the type of the return value
* @return an arbitrary object, as returned by the {@link ResponseExtractor}
* @throws RestClientException on-client side HTTP error
* @see RestTemplate#execute(java.net.URI, org.springframework.http.HttpMethod,
* org.springframework.web.client.RequestCallback,
* org.springframework.web.client.ResponseExtractor)
*/
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor);
}
/**
* Returns the underlying {@link RestTemplate} that is actually used to perform the
* REST operations.
* @return the restTemplate
*/
public RestTemplate getRestTemplate() {
return this.restTemplate;
}
/**
@ -110,7 +903,12 @@ public class TestRestTemplate extends RestTemplate {
/**
* Enable redirects.
*/
ENABLE_REDIRECTS
ENABLE_REDIRECTS,
/**
* Use a {@link SSLConnectionSocketFactory} with {@link TrustSelfSignedStrategy}.
*/
SSL
}
@ -154,6 +952,22 @@ public class TestRestTemplate extends RestTemplate {
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES)
? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES);
this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS);
if (options.contains(HttpClientOption.SSL)) {
setHttpClient(createSslHttpClient());
}
}
private HttpClient createSslHttpClient() {
try {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build());
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create SSL HttpClient", ex);
}
}
@Override
@ -172,4 +986,12 @@ public class TestRestTemplate extends RestTemplate {
}
private static class NoOpResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}
}

@ -16,15 +16,24 @@
package org.springframework.boot.test.web.client;
import java.lang.reflect.Method;
import java.net.URI;
import org.apache.http.client.config.RequestConfig;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate.CustomHttpComponentsClientHttpRequestFactory;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link TestRestTemplate}.
@ -37,14 +46,15 @@ public class TestRestTemplateTests {
@Test
public void simple() {
// The Apache client is on the classpath so we get the fully-fledged factory
assertThat(new TestRestTemplate().getRequestFactory())
assertThat(new TestRestTemplate().getRestTemplate().getRequestFactory())
.isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
}
@Test
public void authenticated() {
assertThat(new TestRestTemplate("user", "password").getRequestFactory())
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
assertThat(new TestRestTemplate("user", "password").getRestTemplate()
.getRequestFactory())
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
}
@Test
@ -52,9 +62,59 @@ public class TestRestTemplateTests {
TestRestTemplate template = new TestRestTemplate(
HttpClientOption.ENABLE_REDIRECTS);
CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template
.getRequestFactory();
.getRestTemplate().getRequestFactory();
RequestConfig config = factory.getRequestConfig();
assertThat(config.isRedirectsEnabled()).isTrue();
}
@Test
public void restOperationsAreAvailable() throws Exception {
RestTemplate delegate = mock(RestTemplate.class);
final TestRestTemplate restTemplate = new TestRestTemplate(delegate);
ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() {
@Override
public void doWith(Method method)
throws IllegalArgumentException, IllegalAccessException {
Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class,
method.getName(), method.getParameterTypes());
try {
equivalent.invoke(restTemplate,
mockArguments(method.getParameterTypes()));
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private Object[] mockArguments(Class<?>[] parameterTypes) throws Exception {
Object[] arguments = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
arguments[i] = mockArgument(parameterTypes[i]);
}
return arguments;
}
private Object mockArgument(Class<?> type) throws Exception {
if (String.class.equals(type)) {
return "String";
}
if (Object[].class.equals(type)) {
return new Object[0];
}
if (URI.class.equals(type)) {
return new URI("http://localhost");
}
if (HttpMethod.class.equals(type)) {
return HttpMethod.GET;
}
if (Class.class.equals(type)) {
return Object.class;
}
return mock(type);
}
});
}
}

Loading…
Cancel
Save