Merge pull request #12148 from hkhan/JAVA-8151-update-spring-webclient
Java 8151 update spring webclient
This commit is contained in:
commit
e825abd158
@ -1,24 +1,14 @@
|
|||||||
package com.baeldung.reactive.webclient;
|
package com.baeldung.reactive.webclient;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class Foo {
|
public class Foo {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
public Foo() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Foo(String name) {
|
|
||||||
super();
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,10 @@ public class WebClientApplication {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) {
|
public SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
|
||||||
http.authorizeExchange()
|
http.csrf().disable()
|
||||||
.anyExchange()
|
.authorizeExchange()
|
||||||
.permitAll();
|
.anyExchange().permitAll();
|
||||||
http.csrf().disable();
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -45,41 +45,41 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
public class WebClientIntegrationTest {
|
public class WebClientIntegrationTest {
|
||||||
|
|
||||||
@LocalServerPort
|
|
||||||
private int port;
|
|
||||||
|
|
||||||
private static final String BODY_VALUE = "bodyValue";
|
private static final String BODY_VALUE = "bodyValue";
|
||||||
private static final ParameterizedTypeReference<Map<String, String>> MAP_RESPONSE_REF = new ParameterizedTypeReference<Map<String, String>>() {
|
private static final ParameterizedTypeReference<Map<String, String>> MAP_RESPONSE_REF = new ParameterizedTypeReference<Map<String, String>>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@LocalServerPort
|
||||||
|
private int port;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() {
|
public void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() {
|
||||||
// WebClient creation
|
// WebClient creation
|
||||||
WebClient client1 = WebClient.create();
|
WebClient client1 = WebClient.create();
|
||||||
WebClient client2 = WebClient.create("http://localhost:" + port);
|
WebClient client2 = WebClient.create("http://localhost:" + port);
|
||||||
WebClient client3 = WebClient.builder()
|
WebClient client3 = WebClient.builder()
|
||||||
.baseUrl("http://localhost:" + port)
|
.baseUrl("http://localhost:" + port)
|
||||||
.defaultCookie("cookieKey", "cookieValue")
|
.defaultCookie("cookieKey", "cookieValue")
|
||||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||||
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
|
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(retrieveResponse(client1.post()
|
StepVerifier.create(retrieveResponse(client1.post()
|
||||||
.uri("http://localhost:" + port + "/resource")))
|
.uri("http://localhost:" + port + "/resource")))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(client2))
|
StepVerifier.create(retrieveResponse(client2))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(client3))
|
StepVerifier.create(retrieveResponse(client3))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
// assert response without specifying URI
|
// assert response without specifying URI
|
||||||
StepVerifier.create(retrieveResponse(client1))
|
StepVerifier.create(retrieveResponse(client1))
|
||||||
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
||||||
.contains("Connection refused"))
|
.contains("Connection refused"))
|
||||||
.verify();
|
.verify();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -91,60 +91,64 @@ public class WebClientIntegrationTest {
|
|||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(retrieveResponse(uriSpecPost1))
|
StepVerifier.create(retrieveResponse(uriSpecPost1))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(uriSpecPost2))
|
StepVerifier.create(retrieveResponse(uriSpecPost2))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveGetResponse(requestGet))
|
StepVerifier.create(retrieveGetResponse(requestGet))
|
||||||
.expectNextMatches(nextMap -> nextMap.get("field")
|
.expectNextMatches(nextMap -> nextMap.get("field")
|
||||||
.equals("value"))
|
.equals("value"))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() {
|
public void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||||
// uri specification
|
// uri specification
|
||||||
RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource");
|
RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource");
|
||||||
RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(uriBuilder -> uriBuilder.pathSegment("resource")
|
RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(
|
||||||
|
uriBuilder -> uriBuilder.pathSegment("resource")
|
||||||
.build());
|
.build());
|
||||||
RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(URI.create("http://localhost:" + port + "/resource"));
|
RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(
|
||||||
|
URI.create("http://localhost:" + port + "/resource"));
|
||||||
RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource"));
|
RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource"));
|
||||||
RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder()
|
RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder()
|
||||||
.baseUrl("http://localhost:" + port)
|
.baseUrl("http://localhost:" + port)
|
||||||
.build()
|
.build()
|
||||||
.post()
|
.post()
|
||||||
.uri(URI.create("/resource"));
|
.uri(URI.create("/resource"));
|
||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(retrieveResponse(bodySpecUsingString))
|
StepVerifier.create(retrieveResponse(bodySpecUsingString))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder))
|
StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(bodySpecusingURI))
|
StepVerifier.create(retrieveResponse(bodySpecusingURI))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
// assert sending request overriding base URI
|
// assert sending request overriding base URI
|
||||||
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri))
|
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri))
|
||||||
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
||||||
.contains("Connection refused"))
|
.contains("Connection refused"))
|
||||||
.verify();
|
.verify();
|
||||||
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2))
|
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2))
|
||||||
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
|
||||||
.contains("Connection refused"))
|
.contains("Connection refused"))
|
||||||
.verify();
|
.verify();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() {
|
public void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||||
// request body specifications
|
// request body specifications
|
||||||
RequestHeadersSpec<?> headersSpecPost1 = createDefaultPostResourceRequest().body(BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class));
|
RequestHeadersSpec<?> headersSpecPost1 = createDefaultPostResourceRequest().body(
|
||||||
RequestHeadersSpec<?> headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(BODY_VALUE));
|
BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class));
|
||||||
|
RequestHeadersSpec<?> headersSpecPost2 = createDefaultPostResourceRequest().body(
|
||||||
|
BodyInserters.fromValue(BODY_VALUE));
|
||||||
RequestHeadersSpec<?> headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE);
|
RequestHeadersSpec<?> headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE);
|
||||||
RequestHeadersSpec<?> headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo")
|
RequestHeadersSpec<?> headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo")
|
||||||
.body(Mono.just(new Foo("fooName")), Foo.class);
|
.body(Mono.just(new Foo("fooName")), Foo.class);
|
||||||
BodyInserter<Object, ReactiveHttpOutputMessage> inserterPlainObject = BodyInserters.fromValue(new Object());
|
BodyInserter<Object, ReactiveHttpOutputMessage> inserterPlainObject = BodyInserters.fromValue(new Object());
|
||||||
RequestHeadersSpec<?> headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject);
|
RequestHeadersSpec<?> headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject);
|
||||||
|
|
||||||
@ -152,54 +156,57 @@ public class WebClientIntegrationTest {
|
|||||||
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
||||||
map.add("key1", "multipartValue1");
|
map.add("key1", "multipartValue1");
|
||||||
map.add("key2", "multipartValue2");
|
map.add("key2", "multipartValue2");
|
||||||
BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(map);
|
BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(
|
||||||
|
map);
|
||||||
RequestHeadersSpec<?> headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart")
|
RequestHeadersSpec<?> headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart")
|
||||||
.body(inserterMultipart);
|
.body(inserterMultipart);
|
||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(retrieveResponse(headersSpecPost1))
|
StepVerifier.create(retrieveResponse(headersSpecPost1))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(headersSpecPost2))
|
StepVerifier.create(retrieveResponse(headersSpecPost2))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(headersSpecPost3))
|
StepVerifier.create(retrieveResponse(headersSpecPost3))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(headersSpecFooPost))
|
StepVerifier.create(retrieveResponse(headersSpecFooPost))
|
||||||
.expectNext("processedFoo-fooName")
|
.expectNext("processedFoo-fooName")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(retrieveResponse(headersSpecInserterMultipart))
|
StepVerifier.create(retrieveResponse(headersSpecInserterMultipart))
|
||||||
.expectNext("processed-multipartValue1-multipartValue2")
|
.expectNext("processed-multipartValue1-multipartValue2")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
// assert error plain `new Object()` as request body
|
// assert error plain `new Object()` as request body
|
||||||
StepVerifier.create(retrieveResponse(headersSpecPlainObject))
|
StepVerifier.create(retrieveResponse(headersSpecPlainObject))
|
||||||
.expectError(CodecException.class)
|
.expectError(CodecException.class)
|
||||||
.verify();
|
.verify();
|
||||||
// assert response for request with no body
|
// assert response for request with no body
|
||||||
Mono<Map<String, String>> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> {
|
Mono<Map<String, String>> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(
|
||||||
assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
responseHandler -> {
|
||||||
return responseHandler.bodyToMono(MAP_RESPONSE_REF);
|
assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||||
});
|
return responseHandler.bodyToMono(MAP_RESPONSE_REF);
|
||||||
|
});
|
||||||
StepVerifier.create(responsePostWithNoBody)
|
StepVerifier.create(responsePostWithNoBody)
|
||||||
.expectNextMatches(nextMap -> nextMap.get("error")
|
.expectNextMatches(nextMap -> nextMap.get("error")
|
||||||
.equals("Bad Request"))
|
.equals("Bad Request"))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() {
|
public void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() {
|
||||||
// request header specification
|
// request header specification
|
||||||
RequestHeadersSpec<?> headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
RequestHeadersSpec<?> headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(
|
||||||
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||||
.acceptCharset(StandardCharsets.UTF_8)
|
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
||||||
.ifNoneMatch("*")
|
.acceptCharset(StandardCharsets.UTF_8)
|
||||||
.ifModifiedSince(ZonedDateTime.now());
|
.ifNoneMatch("*")
|
||||||
|
.ifModifiedSince(ZonedDateTime.now());
|
||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders))
|
StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders))
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -209,68 +216,66 @@ public class WebClientIntegrationTest {
|
|||||||
Mono<String> responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> {
|
Mono<String> responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> {
|
||||||
if (response.statusCode() == HttpStatus.OK) {
|
if (response.statusCode() == HttpStatus.OK) {
|
||||||
return response.bodyToMono(String.class);
|
return response.bodyToMono(String.class);
|
||||||
} else if (response.statusCode()
|
} else if (response.statusCode().is4xxClientError()) {
|
||||||
.is4xxClientError()) {
|
|
||||||
return Mono.just("Error response");
|
return Mono.just("Error response");
|
||||||
} else {
|
} else {
|
||||||
return response.createException()
|
return response.createException()
|
||||||
.flatMap(Mono::error);
|
.flatMap(Mono::error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Mono<String> responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> {
|
Mono<String> responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> {
|
||||||
if (response.statusCode() == HttpStatus.OK) {
|
if (response.statusCode() == HttpStatus.OK) {
|
||||||
return response.bodyToMono(String.class);
|
return response.bodyToMono(String.class);
|
||||||
} else if (response.statusCode()
|
} else if (response.statusCode().is4xxClientError()) {
|
||||||
.is4xxClientError()) {
|
|
||||||
return Mono.just("Error response");
|
return Mono.just("Error response");
|
||||||
} else {
|
} else {
|
||||||
return response.createException()
|
return response.createException()
|
||||||
.flatMap(Mono::error);
|
.flatMap(Mono::error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Mono<Map<String, String>> responseGet = createDefaultClient().get()
|
Mono<Map<String, String>> responseGet = createDefaultClient().get()
|
||||||
.uri("/resource")
|
.uri("/resource")
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.bodyToMono(MAP_RESPONSE_REF);
|
.bodyToMono(MAP_RESPONSE_REF);
|
||||||
|
|
||||||
// response assertions
|
// response assertions
|
||||||
StepVerifier.create(responsePostString)
|
StepVerifier.create(responsePostString)
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(responsePostString2)
|
StepVerifier.create(responsePostString2)
|
||||||
.expectNext("processed-bodyValue")
|
.expectNext("processed-bodyValue")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(responsePostNoBody)
|
StepVerifier.create(responsePostNoBody)
|
||||||
.expectNext("Error response")
|
.expectNext("Error response")
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
StepVerifier.create(responseGet)
|
StepVerifier.create(responseGet)
|
||||||
.expectNextMatches(nextMap -> nextMap.get("field")
|
.expectNextMatches(nextMap -> nextMap.get("field")
|
||||||
.equals("value"))
|
.equals("value"))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() {
|
public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() {
|
||||||
HttpClient httpClient = HttpClient.create()
|
HttpClient httpClient = HttpClient.create()
|
||||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
|
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
|
||||||
.responseTimeout(Duration.ofMillis(1000))
|
.responseTimeout(Duration.ofMillis(1000))
|
||||||
.doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS))
|
.doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS))
|
||||||
.addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS)));
|
.addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS)));
|
||||||
|
|
||||||
WebClient timeoutClient = WebClient.builder()
|
WebClient timeoutClient = WebClient.builder()
|
||||||
.baseUrl("http://localhost:" + port)
|
.baseUrl("http://localhost:" + port)
|
||||||
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
RequestHeadersSpec<?> neverendingMonoBodyRequest = timeoutClient.post()
|
RequestHeadersSpec<?> neverendingMonoBodyRequest = timeoutClient.post()
|
||||||
.uri("/resource")
|
.uri("/resource")
|
||||||
.body(Mono.never(), String.class);
|
.body(Mono.never(), String.class);
|
||||||
|
|
||||||
StepVerifier.create(neverendingMonoBodyRequest.retrieve()
|
StepVerifier.create(neverendingMonoBodyRequest.retrieve()
|
||||||
.bodyToMono(String.class))
|
.bodyToMono(String.class))
|
||||||
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ReadTimeoutException.class.isAssignableFrom(ex.getCause()
|
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass())
|
||||||
.getClass()))
|
&& ReadTimeoutException.class.isAssignableFrom(ex.getCause().getClass()))
|
||||||
.verify();
|
.verify();
|
||||||
}
|
}
|
||||||
|
|
||||||
// helper methods to create default instances
|
// helper methods to create default instances
|
||||||
@ -293,33 +298,33 @@ public class WebClientIntegrationTest {
|
|||||||
// helper methods to retrieve a response based on different steps of the process (specs)
|
// helper methods to retrieve a response based on different steps of the process (specs)
|
||||||
private Mono<String> retrieveResponse(WebClient client) {
|
private Mono<String> retrieveResponse(WebClient client) {
|
||||||
return client.post()
|
return client.post()
|
||||||
.uri("/resource")
|
.uri("/resource")
|
||||||
.bodyValue(BODY_VALUE)
|
.bodyValue(BODY_VALUE)
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.bodyToMono(String.class);
|
.bodyToMono(String.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<String> retrieveResponse(RequestBodyUriSpec spec) {
|
private Mono<String> retrieveResponse(RequestBodyUriSpec spec) {
|
||||||
return spec.uri("/resource")
|
return spec.uri("/resource")
|
||||||
.bodyValue(BODY_VALUE)
|
.bodyValue(BODY_VALUE)
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.bodyToMono(String.class);
|
.bodyToMono(String.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<Map<String, String>> retrieveGetResponse(RequestHeadersUriSpec<?> spec) {
|
private Mono<Map<String, String>> retrieveGetResponse(RequestHeadersUriSpec<?> spec) {
|
||||||
return spec.uri("/resource")
|
return spec.uri("/resource")
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.bodyToMono(MAP_RESPONSE_REF);
|
.bodyToMono(MAP_RESPONSE_REF);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<String> retrieveResponse(RequestBodySpec spec) {
|
private Mono<String> retrieveResponse(RequestBodySpec spec) {
|
||||||
return spec.bodyValue(BODY_VALUE)
|
return spec.bodyValue(BODY_VALUE)
|
||||||
.retrieve()
|
.retrieve()
|
||||||
.bodyToMono(String.class);
|
.bodyToMono(String.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<String> retrieveResponse(RequestHeadersSpec<?> spec) {
|
private Mono<String> retrieveResponse(RequestHeadersSpec<?> spec) {
|
||||||
return spec.retrieve()
|
return spec.retrieve()
|
||||||
.bodyToMono(String.class);
|
.bodyToMono(String.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
package com.baeldung.reactive.webclient;
|
package com.baeldung.reactive.webclient;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
import org.springframework.boot.web.server.LocalServerPort;
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
import org.springframework.test.annotation.DirtiesContext;
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
|
||||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||||
|
|
||||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS;
|
||||||
@RunWith(SpringRunner.class)
|
|
||||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class)
|
@DirtiesContext(classMode = BEFORE_CLASS)
|
||||||
|
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class)
|
||||||
public class WebControllerIntegrationTest {
|
public class WebControllerIntegrationTest {
|
||||||
|
|
||||||
@LocalServerPort
|
@LocalServerPort
|
||||||
int randomServerPort;
|
private int randomServerPort;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WebTestClient testClient;
|
private WebTestClient testClient;
|
||||||
@ -24,30 +24,26 @@ public class WebControllerIntegrationTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private WebController webController;
|
private WebController webController;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setup() {
|
void setup() {
|
||||||
webController.setServerPort(randomServerPort);
|
webController.setServerPort(randomServerPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||||
testClient.get()
|
testClient.get()
|
||||||
.uri("/tweets-blocking")
|
.uri("/tweets-blocking")
|
||||||
.exchange()
|
.exchange()
|
||||||
.expectStatus()
|
.expectStatus().isOk()
|
||||||
.isOk()
|
.expectBodyList(Tweet.class).hasSize(3);
|
||||||
.expectBodyList(Tweet.class)
|
|
||||||
.hasSize(3);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||||
testClient.get()
|
testClient.get()
|
||||||
.uri("/tweets-non-blocking")
|
.uri("/tweets-non-blocking")
|
||||||
.exchange()
|
.exchange()
|
||||||
.expectStatus()
|
.expectStatus().isOk()
|
||||||
.isOk()
|
.expectBodyList(Tweet.class).hasSize(3);
|
||||||
.expectBodyList(Tweet.class)
|
|
||||||
.hasSize(3);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,6 +3,7 @@ package com.baeldung.reactive.webclient;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||||
import org.springframework.boot.web.server.LocalServerPort;
|
import org.springframework.boot.web.server.LocalServerPort;
|
||||||
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.security.test.context.support.WithMockUser;
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
@ -14,7 +15,7 @@ import org.springframework.web.reactive.function.server.ServerResponse;
|
|||||||
import org.springframework.web.server.WebHandler;
|
import org.springframework.web.server.WebHandler;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||||
public class WebTestClientIntegrationTest {
|
public class WebTestClientIntegrationTest {
|
||||||
|
|
||||||
@LocalServerPort
|
@LocalServerPort
|
||||||
@ -26,73 +27,61 @@ public class WebTestClientIntegrationTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private WebClientController controller;
|
private WebClientController controller;
|
||||||
|
|
||||||
private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok()
|
|
||||||
.build());
|
|
||||||
private final WebHandler WEB_HANDLER = exchange -> Mono.empty();
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testWebTestClientWithServerWebHandler() {
|
public void whenBindToWebHandler_thenRequestProcessed() {
|
||||||
WebTestClient.bindToWebHandler(WEB_HANDLER)
|
WebHandler webHandler = exchange -> Mono.empty();
|
||||||
.build();
|
|
||||||
|
WebTestClient.bindToWebHandler(webHandler)
|
||||||
|
.build()
|
||||||
|
.get()
|
||||||
|
.exchange()
|
||||||
|
.expectBody().isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testWebTestClientWithRouterFunction() {
|
public void whenBindToRouter_thenRequestProcessed() {
|
||||||
WebTestClient.bindToRouterFunction(ROUTER_FUNCTION)
|
RouterFunction<ServerResponse> routerFunction = RouterFunctions.route(
|
||||||
.build()
|
RequestPredicates.GET("/resource"),
|
||||||
.get()
|
request -> ServerResponse.ok().build()
|
||||||
.uri("/resource")
|
);
|
||||||
.exchange()
|
|
||||||
.expectStatus()
|
WebTestClient.bindToRouterFunction(routerFunction)
|
||||||
.isOk()
|
.build()
|
||||||
.expectBody()
|
.get().uri("/resource")
|
||||||
.isEmpty();
|
.exchange()
|
||||||
|
.expectStatus().isOk()
|
||||||
|
.expectBody().isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser
|
@WithMockUser
|
||||||
public void testWebTestClientWithServerURL() {
|
public void whenBindToServer_thenRequestProcessed() {
|
||||||
WebTestClient.bindToServer()
|
WebTestClient.bindToServer()
|
||||||
.baseUrl("http://localhost:" + port)
|
.baseUrl("http://localhost:" + port).build()
|
||||||
.build()
|
.get().uri("/resource")
|
||||||
.get()
|
.exchange()
|
||||||
.uri("/resource")
|
.expectStatus().isOk()
|
||||||
.exchange()
|
.expectBody().jsonPath("field").isEqualTo("value");
|
||||||
.expectStatus()
|
|
||||||
.isOk()
|
|
||||||
.expectBody()
|
|
||||||
.jsonPath("field")
|
|
||||||
.isEqualTo("value");
|
|
||||||
;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser
|
@WithMockUser
|
||||||
public void testWebTestClientWithApplicationContext() {
|
public void whenBindToApplicationContext_thenRequestProcessed() {
|
||||||
WebTestClient.bindToApplicationContext(context)
|
WebTestClient.bindToApplicationContext(context)
|
||||||
.build()
|
.build()
|
||||||
.get()
|
.get().uri("/resource")
|
||||||
.uri("/resource")
|
.exchange()
|
||||||
.exchange()
|
.expectStatus().isOk()
|
||||||
.expectStatus()
|
.expectBody().jsonPath("field").isEqualTo("value");
|
||||||
.isOk()
|
|
||||||
.expectBody()
|
|
||||||
.jsonPath("field")
|
|
||||||
.isEqualTo("value");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testWebTestClientWithController() {
|
public void whenBindToController_thenRequestProcessed() {
|
||||||
WebTestClient.bindToController(controller)
|
WebTestClient.bindToController(controller)
|
||||||
.build()
|
.build()
|
||||||
.get()
|
.get().uri("/resource")
|
||||||
.uri("/resource")
|
.exchange()
|
||||||
.exchange()
|
.expectStatus().isOk()
|
||||||
.expectStatus()
|
.expectBody().jsonPath("field").isEqualTo("value");
|
||||||
.isOk()
|
|
||||||
.expectBody()
|
|
||||||
.jsonPath("field")
|
|
||||||
.isEqualTo("value");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user