Remove AsyncRestTemplate and related types

This commit is contained in:
Rossen Stoyanchev
2021-10-08 17:59:03 +01:00
parent 932291b867
commit e3b48c23dd
40 changed files with 37 additions and 4813 deletions

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.http.client;
import java.io.IOException;
import java.net.URI;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SettableListenableFuture;
/**
* An extension of {@link MockClientHttpRequest} that also implements
* {@link org.springframework.http.client.AsyncClientHttpRequest} by wrapping the response in a
* {@link SettableListenableFuture}.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.1
* @deprecated as of Spring 5.0, with no direct replacement
*/
@Deprecated
public class MockAsyncClientHttpRequest extends MockClientHttpRequest implements org.springframework.http.client.AsyncClientHttpRequest {
public MockAsyncClientHttpRequest() {
}
public MockAsyncClientHttpRequest(HttpMethod httpMethod, URI uri) {
super(httpMethod, uri);
}
@Override
public ListenableFuture<ClientHttpResponse> executeAsync() throws IOException {
SettableListenableFuture<ClientHttpResponse> future = new SettableListenableFuture<>();
future.set(execute());
return future;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.test.web.client;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -39,18 +38,10 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
/**
* A {@link ClientHttpRequestFactory} for requests executed via {@link MockMvc}.
*
* <p>As of 5.0 this class also implements
* {@link org.springframework.http.client.AsyncClientHttpRequestFactory
* AsyncClientHttpRequestFactory}. However note that
* {@link org.springframework.web.client.AsyncRestTemplate} and related classes
* have been deprecated at the same time.
*
* @author Rossen Stoyanchev
* @since 3.2
*/
@SuppressWarnings("deprecation")
public class MockMvcClientHttpRequestFactory
implements ClientHttpRequestFactory, org.springframework.http.client.AsyncClientHttpRequestFactory {
public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory {
private final MockMvc mockMvc;
@@ -65,22 +56,12 @@ public class MockMvcClientHttpRequestFactory
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
return new MockClientHttpRequest(httpMethod, uri) {
@Override
public ClientHttpResponse executeInternal() throws IOException {
public ClientHttpResponse executeInternal() {
return getClientHttpResponse(httpMethod, uri, getHeaders(), getBodyAsBytes());
}
};
}
@Override
public org.springframework.http.client.AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod method) {
return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(method, uri) {
@Override
protected ClientHttpResponse executeInternal() throws IOException {
return getClientHttpResponse(method, uri, getHeaders(), getBodyAsBytes());
}
};
}
private ClientHttpResponse getClientHttpResponse(
HttpMethod httpMethod, URI uri, HttpHeaders requestHeaders, byte[] requestBody) {

View File

@@ -25,7 +25,7 @@ import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.support.RestGatewaySupport;
@@ -64,7 +64,6 @@ import org.springframework.web.client.support.RestGatewaySupport;
* @author Rossen Stoyanchev
* @since 3.2
*/
@SuppressWarnings("deprecation")
public final class MockRestServiceServer {
private final RequestExpectationManager expectationManager;
@@ -147,18 +146,6 @@ public final class MockRestServiceServer {
return new DefaultBuilder(restTemplate);
}
/**
* Return a builder for a {@code MockRestServiceServer} that should be used
* to reply to the given {@code AsyncRestTemplate}.
* @since 4.3
* @deprecated see deprecation notice on
* {@link org.springframework.web.client.AsyncRestTemplate} itself
*/
@Deprecated
public static MockRestServiceServerBuilder bindTo(org.springframework.web.client.AsyncRestTemplate asyncRestTemplate) {
return new DefaultBuilder(asyncRestTemplate);
}
/**
* Return a builder for a {@code MockRestServiceServer} that should be used
* to reply to the given {@code RestGatewaySupport}.
@@ -179,18 +166,6 @@ public final class MockRestServiceServer {
return bindTo(restTemplate).build();
}
/**
* A shortcut for {@code bindTo(asyncRestTemplate).build()}.
* @param asyncRestTemplate the AsyncRestTemplate to set up for mock testing
* @return the created mock server
* @deprecated see deprecation notice on
* {@link org.springframework.web.client.AsyncRestTemplate} itself
*/
@Deprecated
public static MockRestServiceServer createServer(org.springframework.web.client.AsyncRestTemplate asyncRestTemplate) {
return bindTo(asyncRestTemplate).build();
}
/**
* A shortcut for {@code bindTo(restGateway).build()}.
* @param restGateway the REST gateway to set up for mock testing
@@ -226,8 +201,8 @@ public final class MockRestServiceServer {
/**
* Build the {@code MockRestServiceServer} and set up the underlying
* {@code RestTemplate} or {@code AsyncRestTemplate} with a
* {@link ClientHttpRequestFactory} that creates mock requests.
* {@code RestTemplate} with a {@link ClientHttpRequestFactory} that
* creates mock requests.
*/
MockRestServiceServer build();
@@ -241,12 +216,8 @@ public final class MockRestServiceServer {
private static class DefaultBuilder implements MockRestServiceServerBuilder {
@Nullable
private final RestTemplate restTemplate;
@Nullable
private final org.springframework.web.client.AsyncRestTemplate asyncRestTemplate;
private boolean ignoreExpectOrder;
private boolean bufferContent;
@@ -255,13 +226,6 @@ public final class MockRestServiceServer {
public DefaultBuilder(RestTemplate restTemplate) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
this.restTemplate = restTemplate;
this.asyncRestTemplate = null;
}
public DefaultBuilder(org.springframework.web.client.AsyncRestTemplate asyncRestTemplate) {
Assert.notNull(asyncRestTemplate, "AsyncRestTemplate must not be null");
this.restTemplate = null;
this.asyncRestTemplate = asyncRestTemplate;
}
@Override
@@ -290,16 +254,11 @@ public final class MockRestServiceServer {
public MockRestServiceServer build(RequestExpectationManager manager) {
MockRestServiceServer server = new MockRestServiceServer(manager);
MockClientHttpRequestFactory factory = server.new MockClientHttpRequestFactory();
if (this.restTemplate != null) {
if (this.bufferContent) {
this.restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
}
else {
this.restTemplate.setRequestFactory(factory);
}
if (this.bufferContent) {
this.restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
}
if (this.asyncRestTemplate != null) {
this.asyncRestTemplate.setAsyncRequestFactory(factory);
else {
this.restTemplate.setRequestFactory(factory);
}
return server;
}
@@ -310,28 +269,18 @@ public final class MockRestServiceServer {
* Mock ClientHttpRequestFactory that creates requests by iterating
* over the list of expected {@link DefaultRequestExpectation}'s.
*/
private class MockClientHttpRequestFactory implements ClientHttpRequestFactory,
org.springframework.http.client.AsyncClientHttpRequestFactory {
private class MockClientHttpRequestFactory implements ClientHttpRequestFactory {
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
return createRequestInternal(uri, httpMethod);
}
@Override
public org.springframework.http.client.AsyncClientHttpRequest createAsyncRequest(
URI uri, HttpMethod httpMethod) {
return createRequestInternal(uri, httpMethod);
}
private org.springframework.mock.http.client.MockAsyncClientHttpRequest createRequestInternal(
URI uri, HttpMethod httpMethod) {
private MockClientHttpRequest createRequestInternal(URI uri, HttpMethod httpMethod) {
Assert.notNull(uri, "'uri' must not be null");
Assert.notNull(httpMethod, "'httpMethod' must not be null");
return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(httpMethod, uri) {
return new MockClientHttpRequest(httpMethod, uri) {
@Override
protected ClientHttpResponse executeInternal() throws IOException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,10 +23,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.test.web.client.ExpectedCount.once;
import static org.springframework.test.web.client.ExpectedCount.twice;
@@ -44,15 +44,15 @@ public class DefaultRequestExpectationTests {
@Test
public void match() throws Exception {
RequestExpectation expectation = new DefaultRequestExpectation(once(), requestTo("/foo"));
expectation.match(createRequest(GET, "/foo"));
expectation.match(createRequest());
}
@Test
public void matchWithFailedExpectation() throws Exception {
public void matchWithFailedExpectation() {
RequestExpectation expectation = new DefaultRequestExpectation(once(), requestTo("/foo"));
expectation.andExpect(method(POST));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
expectation.match(createRequest(GET, "/foo")))
expectation.match(createRequest()))
.withMessageContaining("Unexpected HttpMethod expected:<POST> but was:<GET>");
}
@@ -81,10 +81,9 @@ public class DefaultRequestExpectationTests {
}
@SuppressWarnings("deprecation")
private ClientHttpRequest createRequest(HttpMethod method, String url) {
private ClientHttpRequest createRequest() {
try {
return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(method, new URI(url));
return new MockClientHttpRequest(HttpMethod.GET, new URI("/foo"));
}
catch (URISyntaxException ex) {
throw new IllegalStateException(ex);

View File

@@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -42,7 +43,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
*/
public class UnorderedRequestExpectationManagerTests {
private UnorderedRequestExpectationManager manager = new UnorderedRequestExpectationManager();
private final UnorderedRequestExpectationManager manager = new UnorderedRequestExpectationManager();
@Test
@@ -57,7 +58,7 @@ public class UnorderedRequestExpectationManagerTests {
}
@Test
public void zeroExpectedRequests() throws Exception {
public void zeroExpectedRequests() {
this.manager.verify();
}
@@ -108,19 +109,18 @@ public class UnorderedRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/bar"));
this.manager.validateRequest(createRequest(GET, "/foo"));
this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.verify())
.withMessageContaining("3 request(s) executed:\n" +
"GET /bar\n" +
"GET /foo\n" +
"GET /foo\n");
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(this.manager::verify)
.withMessageContaining("3 request(s) executed:\n" +
"GET /bar\n" +
"GET /foo\n" +
"GET /foo\n");
}
@SuppressWarnings("deprecation")
private ClientHttpRequest createRequest(HttpMethod method, String url) {
try {
return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(method, new URI(url));
return new MockClientHttpRequest(method, new URI(url));
}
catch (URISyntaxException ex) {
throw new IllegalStateException(ex);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@@ -31,7 +30,6 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockMvcClientHttpRequestFactory;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@@ -68,21 +66,12 @@ public class MockMvcClientHttpRequestFactoryTests {
}
@Test
public void test() throws Exception {
public void test() {
RestTemplate template = new RestTemplate(new MockMvcClientHttpRequestFactory(this.mockMvc));
String result = template.getForObject("/foo", String.class);
assertThat(result).isEqualTo("bar");
}
@Test
@SuppressWarnings("deprecation")
public void testAsyncTemplate() throws Exception {
org.springframework.web.client.AsyncRestTemplate template = new org.springframework.web.client.AsyncRestTemplate(
new MockMvcClientHttpRequestFactory(this.mockMvc));
ListenableFuture<ResponseEntity<String>> entity = template.getForEntity("/foo", String.class);
assertThat(entity.get().getBody()).isEqualTo("bar");
}
@EnableWebMvc
@Configuration

View File

@@ -1,144 +0,0 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.concurrent.ListenableFuture;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.ExpectedCount.manyTimes;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* Examples to demonstrate writing client-side REST tests with Spring MVC Test.
* While the tests in this class invoke the RestTemplate directly, in actual
* tests the RestTemplate may likely be invoked indirectly, i.e. through client
* code.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
@SuppressWarnings("deprecation")
public class SampleAsyncTests {
private final org.springframework.web.client.AsyncRestTemplate restTemplate = new org.springframework.web.client.AsyncRestTemplate();
private final MockRestServiceServer mockServer = MockRestServiceServer.createServer(this.restTemplate);
@Test
public void performGet() throws Exception {
String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
ListenableFuture<ResponseEntity<Person>> ludwig =
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
// We are only validating the request. The response is mocked out.
// person.getName().equals("Ludwig van Beethoven")
// person.getDouble().equals(1.6035)
this.mockServer.verify();
}
@Test
public void performGetManyTimes() throws Exception {
String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
this.mockServer.expect(manyTimes(), requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
ListenableFuture<ResponseEntity<Person>> ludwig =
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
// We are only validating the request. The response is mocked out.
// person.getName().equals("Ludwig van Beethoven")
// person.getDouble().equals(1.6035)
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
this.mockServer.verify();
}
@Test
public void performGetWithResponseBodyFromFile() throws Exception {
Resource responseBody = new ClassPathResource("ludwig.json", this.getClass());
this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
ListenableFuture<ResponseEntity<Person>> ludwig =
this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);
// hotel.getId() == 42
// hotel.getName().equals("Holiday Inn")
this.mockServer.verify();
}
@Test
public void verify() {
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("1", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("2", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("4", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("8", MediaType.TEXT_PLAIN));
@SuppressWarnings("unused")
ListenableFuture<ResponseEntity<String>> result = this.restTemplate.getForEntity("/number", String.class);
// result == "1"
result = this.restTemplate.getForEntity("/number", String.class);
// result == "2"
try {
this.mockServer.verify();
}
catch (AssertionError error) {
assertThat(error.getMessage().contains("2 unsatisfied expectation(s)")).as(error.getMessage()).isTrue();
}
}
}