JAVA-24463 Rollback the changes in the spring-reactive and spring-5-reactive (#14845)
Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
-17
@@ -1,17 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.reactive.Spring5ReactiveApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Spring5ReactiveApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
package com.baeldung.functional;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromValue;
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.reactive.function.BodyInserters;
|
||||
|
||||
public class FunctionalWebApplicationIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
private static WebServer server;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
server = new FunctionalWebApplication().start();
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + server.getPort())
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
|
||||
client.get()
|
||||
.uri("/test")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
|
||||
client.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("helloworld");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
|
||||
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
|
||||
formData.add("user", "baeldung");
|
||||
formData.add("token", "you_know_what_to_do");
|
||||
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("welcome back!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
|
||||
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
|
||||
formData.add("user", "baeldung");
|
||||
formData.add("token", "try_again");
|
||||
|
||||
client.post()
|
||||
.uri("/login")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.body(BodyInserters.fromFormData(formData))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isBadRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
|
||||
Resource resource = new ClassPathResource("/baeldung-weekly.png");
|
||||
client.post()
|
||||
.uri("/upload")
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(fromResource(resource))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo(String.valueOf(resource.contentLength()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActors_whenAddActor_thenAdded() throws Exception {
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(2);
|
||||
|
||||
client.post()
|
||||
.uri("/actor")
|
||||
.body(fromValue(new Actor("Clint", "Eastwood")))
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
|
||||
client.get()
|
||||
.uri("/actor")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Actor.class)
|
||||
.hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResources_whenAccess_thenGot() throws Exception {
|
||||
client.get()
|
||||
.uri("/files/hello.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("hello");
|
||||
}
|
||||
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.reactive;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Random;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.reactive.model.Foo;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class FluxUnitTest {
|
||||
|
||||
public static final Random RANDOM = new Random();
|
||||
|
||||
@Test
|
||||
public void whenFluxIsConstructed_thenCorrect() {
|
||||
final Flux<Foo> flux = Flux.<Foo> create(fluxSink -> {
|
||||
for (int i = 0 ; i < 100 ; i++) {
|
||||
fluxSink.next(new Foo(RANDOM.nextLong(), randomAlphabetic(6)));
|
||||
}
|
||||
}).sample(Duration.ofSeconds(1)).log();
|
||||
|
||||
flux.subscribe();
|
||||
|
||||
assertNotNull(flux);
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.reactive.debugging.consumer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.baeldung.reactive.debugging.consumer.model.Foo;
|
||||
import com.baeldung.reactive.debugging.consumer.service.FooService;
|
||||
import com.baeldung.reactive.debugging.consumer.utils.ListAppender;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.classic.spi.IThrowableProxy;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Hooks;
|
||||
|
||||
class ConsumerFooServiceIntegrationTest {
|
||||
|
||||
FooService service = new FooService();
|
||||
|
||||
@BeforeEach
|
||||
void clearLogList() {
|
||||
Hooks.onOperatorDebug();
|
||||
ListAppender.clearEventList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFooWithNullId_whenProcessFoo_thenLogsWithDebugTrace() {
|
||||
Foo one = new Foo(1, "nameverylong", 8);
|
||||
Foo two = new Foo(null, "nameverylong", 4);
|
||||
Flux<Foo> flux = Flux.just(one, two);
|
||||
|
||||
service.processFoo(flux);
|
||||
|
||||
Collection<String> allLoggedEntries = ListAppender.getEvents()
|
||||
.stream()
|
||||
.map(ILoggingEvent::getFormattedMessage)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Collection<String> allSuppressedEntries = ListAppender.getEvents()
|
||||
.stream()
|
||||
.map(ILoggingEvent::getThrowableProxy)
|
||||
.flatMap(t -> Optional.ofNullable(t)
|
||||
.map(IThrowableProxy::getSuppressed)
|
||||
.map(Arrays::stream)
|
||||
.orElse(Stream.empty()))
|
||||
.map(IThrowableProxy::getClassName)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(allLoggedEntries)
|
||||
.anyMatch(entry -> entry.contains("The following error happened on processFoo method!"))
|
||||
.anyMatch(entry -> entry.contains("| onSubscribe"))
|
||||
.anyMatch(entry -> entry.contains("| cancel()"));
|
||||
|
||||
assertThat(allSuppressedEntries)
|
||||
.anyMatch(entry -> entry.contains("reactor.core.publisher.FluxOnAssembly$OnAssemblyException"));
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.reactive.debugging.consumer;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
|
||||
|
||||
/**
|
||||
* In order to run this live test, start the following classes:
|
||||
* - com.baeldung.reactive.debugging.server.ServerDebuggingApplication
|
||||
* - com.baeldung.reactive.debugging.consumer.ConsumerDebuggingApplication
|
||||
*/
|
||||
class ConsumerFooServiceLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8082";
|
||||
private static final String DEBUG_HOOK_ON = BASE_URL + "/debug-hook-on";
|
||||
private static final String DEBUG_HOOK_OFF = BASE_URL + "/debug-hook-off";
|
||||
|
||||
private static WebTestClient client;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl(BASE_URL)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRequestingDebugHookOn_thenObtainExpectedMessage() {
|
||||
ResponseSpec response = client.get()
|
||||
.uri(DEBUG_HOOK_ON)
|
||||
.exchange();
|
||||
response.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("DEBUG HOOK ON");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRequestingDebugHookOff_thenObtainExpectedMessage() {
|
||||
ResponseSpec response = client.get()
|
||||
.uri(DEBUG_HOOK_OFF)
|
||||
.exchange();
|
||||
response.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("DEBUG HOOK OFF");
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.reactive.debugging.consumer.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ListAppender extends AppenderBase<ILoggingEvent> {
|
||||
|
||||
private static final List<ILoggingEvent> EVENTS = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
EVENTS.add(eventObject);
|
||||
}
|
||||
|
||||
public static List<ILoggingEvent> getEvents() {
|
||||
return EVENTS;
|
||||
}
|
||||
|
||||
public static void clearEventList() {
|
||||
EVENTS.clear();
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.reactive.introduction;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.reactivestreams.Subscriber;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.ConnectableFlux;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class ReactorIntegrationTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ReactorIntegrationTest.class);
|
||||
|
||||
@Test
|
||||
void givenFlux_whenSubscribing_thenStream() {
|
||||
|
||||
List<Integer> elements = new ArrayList<>();
|
||||
|
||||
Flux.just(1, 2, 3, 4)
|
||||
.log()
|
||||
.map(i -> {
|
||||
LOGGER.debug("{}:{}", i, Thread.currentThread());
|
||||
return i * 2;
|
||||
})
|
||||
.subscribe(elements::add);
|
||||
|
||||
assertThat(elements).containsExactly(2, 4, 6, 8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFlux_whenZipping_thenCombine() {
|
||||
List<String> elements = new ArrayList<>();
|
||||
|
||||
Flux.just(1, 2, 3, 4)
|
||||
.log()
|
||||
.map(i -> i * 2)
|
||||
.zipWith(Flux.range(0, Integer.MAX_VALUE).log(), (one, two) -> String.format("First Flux: %d, Second Flux: %d", one, two))
|
||||
.subscribe(elements::add);
|
||||
|
||||
assertThat(elements).containsExactly(
|
||||
"First Flux: 2, Second Flux: 0",
|
||||
"First Flux: 4, Second Flux: 1",
|
||||
"First Flux: 6, Second Flux: 2",
|
||||
"First Flux: 8, Second Flux: 3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() {
|
||||
|
||||
List<Integer> elements = new ArrayList<>();
|
||||
|
||||
Flux.just(1, 2, 3, 4)
|
||||
.log()
|
||||
.subscribe(new Subscriber<Integer>() {
|
||||
private Subscription s;
|
||||
int onNextAmount;
|
||||
|
||||
@Override
|
||||
public void onSubscribe(final Subscription s) {
|
||||
this.s = s;
|
||||
s.request(2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(final Integer integer) {
|
||||
elements.add(integer);
|
||||
onNextAmount++;
|
||||
if (onNextAmount % 2 == 0) {
|
||||
s.request(2);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Throwable t) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(elements).containsExactly(1, 2, 3, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFlux_whenInParallel_thenSubscribeInDifferentThreads() throws InterruptedException {
|
||||
List<String> threadNames = new ArrayList<>();
|
||||
|
||||
Flux.just(1, 2, 3, 4)
|
||||
.log()
|
||||
.map(i -> Thread.currentThread().getName())
|
||||
.subscribeOn(Schedulers.parallel())
|
||||
.subscribe(threadNames::add);
|
||||
|
||||
Thread.sleep(1000);
|
||||
|
||||
assertThat(threadNames).isNotEmpty();
|
||||
assertThat(threadNames).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenConnectableFlux_whenConnected_thenShouldStream() {
|
||||
|
||||
List<Integer> elements = new ArrayList<>();
|
||||
|
||||
final ConnectableFlux<Integer> publish = Flux.just(1, 2, 3, 4).publish();
|
||||
|
||||
publish.subscribe(elements::add);
|
||||
|
||||
assertThat(elements).isEmpty();
|
||||
|
||||
publish.connect();
|
||||
|
||||
assertThat(elements).containsExactly(1, 2, 3, 4);
|
||||
}
|
||||
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.reactive.responseheaders;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class ResponseHeaderLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8080";
|
||||
private static final String ANNOTATION_BASE_URL = BASE_URL + "/response-header";
|
||||
private static final String FUNCTIONAL_BASE_URL = BASE_URL + "/functional-response-header";
|
||||
private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header";
|
||||
private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header";
|
||||
private static final String SERVICE_FILTER_RESPONSE_HEADER_VALUE = "Value-Filter";
|
||||
|
||||
private static WebTestClient client;
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl(BASE_URL)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl(BASE_URL)
|
||||
.build();
|
||||
ResponseSpec response = client.get()
|
||||
.uri(ANNOTATION_BASE_URL + "/response-entity")
|
||||
.exchange();
|
||||
|
||||
response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-ResponseEntityBuilder")
|
||||
.expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingServerHttpResponseRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
ResponseSpec response = client.get()
|
||||
.uri(ANNOTATION_BASE_URL + "/server-http-response")
|
||||
.exchange();
|
||||
|
||||
response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-ServerHttpResponse")
|
||||
.expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFunctionalHandlerRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
ResponseSpec response = client.get()
|
||||
.uri(FUNCTIONAL_BASE_URL + "/single-handler")
|
||||
.exchange();
|
||||
|
||||
response.expectHeader().valueEquals(SERVICE_SINGLE_RESPONSE_HEADER, "Value-Handler")
|
||||
.expectHeader().valueEquals(SERVICE_FILTER_RESPONSE_HEADER, SERVICE_FILTER_RESPONSE_HEADER_VALUE);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.reactive.security;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
@SpringBootTest(classes = SpringSecurity6Application.class)
|
||||
class SecurityIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext context;
|
||||
|
||||
private WebTestClient webTestClient;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
webTestClient = WebTestClient.bindToApplicationContext(context)
|
||||
.configureClient()
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenNoCredentials_thenRedirectToLogin() {
|
||||
webTestClient.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().is3xxRedirection();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void whenHasCredentials_thenSeesGreeting() {
|
||||
webTestClient.get()
|
||||
.uri("/")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(String.class).isEqualTo("Hello, user");
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package com.baeldung.reactive.urlmatch;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
private static WebServer server;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
server = new ExploreSpring5URLPatternUsingRouterFunctions().start();
|
||||
client = WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + server.getPort())
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetPathWithSingleCharWildcard_thenGotPathPattern() throws Exception {
|
||||
client.get()
|
||||
.uri("/test")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("Path /t?st is accessed");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenMultipleURIVariablePattern_thenGotPathVariable() throws Exception {
|
||||
client.get()
|
||||
.uri("/test/ab/cd")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("/ab/cd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetMultipleCharWildcard_thenGotPathPattern() throws Exception {
|
||||
|
||||
client.get()
|
||||
.uri("/baeldung/tutorialId")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("/baeldung/*Id path was accessed");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetMultiplePathVaribleInSameSegment_thenGotPathVariables() throws Exception {
|
||||
|
||||
client.get()
|
||||
.uri("/baeldung_tutorial")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("baeldung , tutorial");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenGetRegexInPathVarible_thenGotPathVariable() throws Exception {
|
||||
|
||||
client.get()
|
||||
.uri("/abcd")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("/{baeldung:[a-z]+} was accessed and baeldung=abcd");
|
||||
|
||||
client.get()
|
||||
.uri("/1234")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is4xxClientError();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResources_whenAccess_thenGot() throws Exception {
|
||||
client.get()
|
||||
.uri("/files/test/test.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("test");
|
||||
|
||||
client.get()
|
||||
.uri("/files/hello.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRouter_whenAccess_thenGot() throws Exception {
|
||||
client.get()
|
||||
.uri("/resources/test/test.txt")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("test");
|
||||
}
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
package com.baeldung.reactive.urlmatch;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import com.baeldung.reactive.Spring5ReactiveApplication;
|
||||
import com.baeldung.reactive.controller.PathPatternController;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Spring5ReactiveApplication.class)
|
||||
@WithMockUser
|
||||
public class PathPatternsUsingHandlerMethodIntegrationTest {
|
||||
|
||||
private static WebTestClient client;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
client = WebTestClient.bindToController(new PathPatternController())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenMultipleURIVariablePattern_then200() {
|
||||
|
||||
client.get()
|
||||
.uri("/spring5/baeldung/tutorial")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("/baeldung/tutorial");
|
||||
|
||||
client.get()
|
||||
.uri("/spring5/baeldung")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("/baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMoreChar_then200() {
|
||||
|
||||
client.get()
|
||||
.uri("/spring5/userid")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("/spring5/*id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenURLWithWildcardTakingExactlyOneChar_then200() {
|
||||
|
||||
client.get()
|
||||
.uri("/string5")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("/s?ring5");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenURLWithWildcardTakingZeroOrMorePathSegments_then200() {
|
||||
|
||||
client.get()
|
||||
.uri("/resources/baeldung")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("/resources/**");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenURLWithRegexInPathVariable_thenExpectedOutput() {
|
||||
|
||||
client.get()
|
||||
.uri("/abc")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("abc");
|
||||
|
||||
client.get()
|
||||
.uri("/123")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is4xxClientError();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHandlerMethod_whenURLWithMultiplePathVariablesInSameSegment_then200() {
|
||||
|
||||
client.get()
|
||||
.uri("/baeldung_tutorial")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody()
|
||||
.equals("Two variables are var1=baeldung and var2=tutorial");
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.reactive.webclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest(classes = WebClientApplication.class)
|
||||
class SpringContextTest {
|
||||
|
||||
@Test
|
||||
void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package com.baeldung.reactive.webclient;
|
||||
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.handler.timeout.ReadTimeoutException;
|
||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||
import io.netty.handler.timeout.WriteTimeoutHandler;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.core.codec.CodecException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ReactiveHttpOutputMessage;
|
||||
import org.springframework.http.client.reactive.ClientHttpRequest;
|
||||
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.reactive.function.BodyInserter;
|
||||
import org.springframework.web.reactive.function.BodyInserters;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestBodyUriSpec;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec;
|
||||
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
|
||||
import org.springframework.web.reactive.function.client.WebClientRequestException;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
class WebClientIntegrationTest {
|
||||
|
||||
private static final String BODY_VALUE = "bodyValue";
|
||||
private static final ParameterizedTypeReference<Map<String, String>> MAP_RESPONSE_REF = new ParameterizedTypeReference<Map<String, String>>() {
|
||||
};
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Test
|
||||
void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() {
|
||||
WebClient client1 = WebClient.builder().clientConnector(httpConnector()).build();
|
||||
StepVerifier.create(retrieveResponse(client1.post()
|
||||
.uri("http://localhost:" + port + "/resource")))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
WebClient client2 = WebClient.builder().baseUrl("http://localhost:" + port)
|
||||
.clientConnector(httpConnector()).build();
|
||||
StepVerifier.create(retrieveResponse(client2))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
WebClient client3 = WebClient.builder()
|
||||
.baseUrl("http://localhost:" + port)
|
||||
.clientConnector(httpConnector())
|
||||
.defaultCookie("cookieKey", "cookieValue")
|
||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080"))
|
||||
.build();
|
||||
StepVerifier.create(retrieveResponse(client3))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDifferentMethodSpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||
|
||||
RequestBodyUriSpec uriSpecPost1 = createDefaultClient().method(HttpMethod.POST);
|
||||
StepVerifier.create(retrieveResponse(uriSpecPost1))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
RequestBodyUriSpec uriSpecPost2 = createDefaultClient().post();
|
||||
StepVerifier.create(retrieveResponse(uriSpecPost2))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
RequestHeadersUriSpec<?> requestGet = createDefaultClient().get();
|
||||
StepVerifier.create(retrieveGetResponse(requestGet))
|
||||
.expectNextMatches(nextMap -> nextMap.get("field")
|
||||
.equals("value"))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||
|
||||
RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource");
|
||||
StepVerifier.create(retrieveResponse(bodySpecUsingString))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(
|
||||
uriBuilder -> uriBuilder.pathSegment("resource")
|
||||
.build());
|
||||
StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(
|
||||
URI.create("http://localhost:" + port + "/resource"));
|
||||
StepVerifier.create(retrieveResponse(bodySpecusingURI))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOverriddenUriSpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||
RequestBodySpec bodySpecOverriddenBaseUri = createDefaultPostRequest()
|
||||
.uri(URI.create("http://localhost:" + port + "/resource-override"));
|
||||
|
||||
StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri))
|
||||
.expectNext("override-processed-bodyValue")
|
||||
.verifyComplete();
|
||||
|
||||
RequestBodySpec bodySpecOverriddenBaseUri2 = WebClient.builder()
|
||||
.clientConnector(httpConnector())
|
||||
.baseUrl("http://localhost:" + port)
|
||||
.build()
|
||||
.post()
|
||||
.uri(URI.create("http://localhost:" + port + "/resource-override"));
|
||||
|
||||
StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri2))
|
||||
.expectNext("override-processed-bodyValue")
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||
// request body specifications
|
||||
RequestHeadersSpec<?> headersSpecPost1 = createDefaultPostResourceRequest().body(
|
||||
BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class));
|
||||
RequestHeadersSpec<?> headersSpecPost2 = createDefaultPostResourceRequest().body(
|
||||
BodyInserters.fromValue(BODY_VALUE));
|
||||
RequestHeadersSpec<?> headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE);
|
||||
RequestHeadersSpec<?> headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo")
|
||||
.body(Mono.just(new Foo("fooName")), Foo.class);
|
||||
BodyInserter<Object, ReactiveHttpOutputMessage> inserterPlainObject = BodyInserters.fromValue(new Object());
|
||||
RequestHeadersSpec<?> headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject);
|
||||
|
||||
// request body specifications - using other inserter method (multipart request)
|
||||
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
||||
map.add("key1", "multipartValue1");
|
||||
map.add("key2", "multipartValue2");
|
||||
BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(
|
||||
map);
|
||||
RequestHeadersSpec<?> headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart")
|
||||
.body(inserterMultipart);
|
||||
|
||||
// response assertions
|
||||
StepVerifier.create(retrieveResponse(headersSpecPost1))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(retrieveResponse(headersSpecPost2))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(retrieveResponse(headersSpecPost3))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(retrieveResponse(headersSpecFooPost))
|
||||
.expectNext("processedFoo-fooName")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(retrieveResponse(headersSpecInserterMultipart))
|
||||
.expectNext("processed-multipartValue1-multipartValue2")
|
||||
.verifyComplete();
|
||||
// assert error plain `new Object()` as request body
|
||||
StepVerifier.create(retrieveResponse(headersSpecPlainObject))
|
||||
.expectError(CodecException.class)
|
||||
.verify();
|
||||
// assert response for request without body
|
||||
Mono<Map<String, String>> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(
|
||||
responseHandler -> {
|
||||
assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
return responseHandler.bodyToMono(MAP_RESPONSE_REF);
|
||||
});
|
||||
StepVerifier.create(responsePostWithNoBody)
|
||||
.expectNextMatches(nextMap -> nextMap.get("error")
|
||||
.equals("Bad Request"))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() {
|
||||
// request header specification
|
||||
RequestHeadersSpec<?> headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(
|
||||
HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
|
||||
.acceptCharset(StandardCharsets.UTF_8)
|
||||
.ifNoneMatch("*")
|
||||
.ifModifiedSince(ZonedDateTime.now());
|
||||
|
||||
// response assertions
|
||||
StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders))
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDifferentResponseSpecifications_whenUsed_thenObtainExpectedResponse() {
|
||||
ResponseSpec responseSpecPostString = createDefaultPostResourceRequestResponse().retrieve();
|
||||
Mono<String> responsePostString = responseSpecPostString.bodyToMono(String.class);
|
||||
Mono<String> responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> {
|
||||
if (response.statusCode() == HttpStatus.OK) {
|
||||
return response.bodyToMono(String.class);
|
||||
} else if (response.statusCode().is4xxClientError()) {
|
||||
return Mono.just("Error response");
|
||||
} else {
|
||||
return response.createException()
|
||||
.flatMap(Mono::error);
|
||||
}
|
||||
});
|
||||
Mono<String> responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> {
|
||||
if (response.statusCode() == HttpStatus.OK) {
|
||||
return response.bodyToMono(String.class);
|
||||
} else if (response.statusCode().is4xxClientError()) {
|
||||
return Mono.just("Error response");
|
||||
} else {
|
||||
return response.createException()
|
||||
.flatMap(Mono::error);
|
||||
}
|
||||
});
|
||||
Mono<Map<String, String>> responseGet = createDefaultClient().get()
|
||||
.uri("/resource")
|
||||
.retrieve()
|
||||
.bodyToMono(MAP_RESPONSE_REF);
|
||||
|
||||
// response assertions
|
||||
StepVerifier.create(responsePostString)
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(responsePostString2)
|
||||
.expectNext("processed-bodyValue")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(responsePostNoBody)
|
||||
.expectNext("Error response")
|
||||
.verifyComplete();
|
||||
StepVerifier.create(responseGet)
|
||||
.expectNextMatches(nextMap -> nextMap.get("field")
|
||||
.equals("value"))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() {
|
||||
HttpClient httpClient = HttpClient.create()
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
|
||||
.responseTimeout(Duration.ofMillis(1000))
|
||||
.doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS))
|
||||
.addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS)));
|
||||
|
||||
WebClient timeoutClient = WebClient.builder()
|
||||
.baseUrl("http://localhost:" + port)
|
||||
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
||||
.build();
|
||||
|
||||
RequestHeadersSpec<?> neverendingMonoBodyRequest = timeoutClient.post()
|
||||
.uri("/resource")
|
||||
.body(Mono.never(), String.class);
|
||||
|
||||
StepVerifier.create(neverendingMonoBodyRequest.retrieve()
|
||||
.bodyToMono(String.class))
|
||||
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass())
|
||||
&& ReadTimeoutException.class.isAssignableFrom(ex.getCause().getClass()))
|
||||
.verify();
|
||||
}
|
||||
|
||||
// helper methods to create default instances
|
||||
private WebClient createDefaultClient() {
|
||||
return WebClient.builder()
|
||||
.baseUrl("http://localhost:" + port)
|
||||
.clientConnector(httpConnector())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ReactorClientHttpConnector httpConnector() {
|
||||
HttpClient httpClient = HttpClient
|
||||
.create()
|
||||
.wiretap(true);
|
||||
return new ReactorClientHttpConnector(httpClient);
|
||||
}
|
||||
|
||||
private RequestBodyUriSpec createDefaultPostRequest() {
|
||||
return createDefaultClient().post();
|
||||
}
|
||||
|
||||
private RequestBodySpec createDefaultPostResourceRequest() {
|
||||
return createDefaultPostRequest().uri("/resource");
|
||||
}
|
||||
|
||||
private RequestHeadersSpec<?> createDefaultPostResourceRequestResponse() {
|
||||
return createDefaultPostResourceRequest().bodyValue(BODY_VALUE);
|
||||
}
|
||||
|
||||
// helper methods to retrieve a response based on different steps of the process (specs)
|
||||
private Mono<String> retrieveResponse(WebClient client) {
|
||||
return client.post()
|
||||
.uri("/resource")
|
||||
.bodyValue(BODY_VALUE)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class);
|
||||
}
|
||||
|
||||
private Mono<String> retrieveResponse(RequestBodyUriSpec spec) {
|
||||
return spec.uri("/resource")
|
||||
.bodyValue(BODY_VALUE)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class);
|
||||
}
|
||||
|
||||
private Mono<Map<String, String>> retrieveGetResponse(RequestHeadersUriSpec<?> spec) {
|
||||
return spec.uri("/resource")
|
||||
.retrieve()
|
||||
.bodyToMono(MAP_RESPONSE_REF);
|
||||
}
|
||||
|
||||
private Mono<String> retrieveResponse(RequestBodySpec spec) {
|
||||
return spec.bodyValue(BODY_VALUE)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class);
|
||||
}
|
||||
|
||||
private Mono<String> retrieveResponse(RequestHeadersSpec<?> spec) {
|
||||
return spec.retrieve()
|
||||
.bodyToMono(String.class);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.reactive.webclient;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS;
|
||||
|
||||
@DirtiesContext(classMode = BEFORE_CLASS)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class)
|
||||
class WebControllerIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
private int randomServerPort;
|
||||
|
||||
@Autowired
|
||||
private WebTestClient testClient;
|
||||
|
||||
@Autowired
|
||||
private WebController webController;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
webController.setServerPort(randomServerPort);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||
testClient.get()
|
||||
.uri("/tweets-blocking")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBodyList(Tweet.class).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() {
|
||||
testClient.get()
|
||||
.uri("/tweets-non-blocking")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBodyList(Tweet.class).hasSize(3);
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.reactive.webclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.web.reactive.function.server.RequestPredicates;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import org.springframework.web.server.WebHandler;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
class WebTestClientIntegrationTest {
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext context;
|
||||
|
||||
@Autowired
|
||||
private WebClientController controller;
|
||||
|
||||
@Test
|
||||
void whenBindToWebHandler_thenRequestProcessed() {
|
||||
WebHandler webHandler = exchange -> Mono.empty();
|
||||
|
||||
WebTestClient.bindToWebHandler(webHandler)
|
||||
.build()
|
||||
.get()
|
||||
.exchange()
|
||||
.expectBody().isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenBindToRouter_thenRequestProcessed() {
|
||||
RouterFunction<ServerResponse> routerFunction = RouterFunctions.route(
|
||||
RequestPredicates.GET("/resource"),
|
||||
request -> ServerResponse.ok().build()
|
||||
);
|
||||
|
||||
WebTestClient.bindToRouterFunction(routerFunction)
|
||||
.build()
|
||||
.get().uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void whenBindToServer_thenRequestProcessed() {
|
||||
WebTestClient.bindToServer()
|
||||
.baseUrl("http://localhost:" + port).build()
|
||||
.get().uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().jsonPath("field").isEqualTo("value");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void whenBindToApplicationContext_thenRequestProcessed() {
|
||||
WebTestClient.bindToApplicationContext(context)
|
||||
.build()
|
||||
.get().uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().jsonPath("field").isEqualTo("value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenBindToController_thenRequestProcessed() {
|
||||
WebTestClient.bindToController(controller)
|
||||
.build()
|
||||
.get().uri("/resource")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().jsonPath("field").isEqualTo("value");
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.baeldung.reactive.webclientrequests;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
|
||||
import org.springframework.web.reactive.function.client.ClientRequest;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.util.DefaultUriBuilderFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@WebFluxTest
|
||||
class WebClientRequestsWithParametersUnitTest {
|
||||
|
||||
private static final String BASE_URL = "https://example.com";
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<ClientRequest> argumentCaptor;
|
||||
|
||||
@Mock
|
||||
private ExchangeFunction exchangeFunction;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
ClientResponse mockResponse = mock(ClientResponse.class);
|
||||
when(mockResponse.bodyToMono(String.class)).thenReturn(Mono.just("test"));
|
||||
when(exchangeFunction.exchange(argumentCaptor.capture())).thenReturn(Mono.just(mockResponse));
|
||||
|
||||
webClient = WebClient
|
||||
.builder()
|
||||
.baseUrl(BASE_URL)
|
||||
.exchangeFunction(exchangeFunction)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallSimpleURI_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri("/products")
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallSinglePathSegmentUri_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/{id}")
|
||||
.build(2))
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallMultiplePathSegmentsUri_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/{id}/attributes/{attributeId}")
|
||||
.build(2, 13))
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/2/attributes/13");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallSingleQueryParams_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("name", "AndroidPhone")
|
||||
.queryParam("color", "black")
|
||||
.queryParam("deliveryDate", "13/04/2019")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallSingleQueryParamsPlaceholders_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("name", "{title}")
|
||||
.queryParam("color", "{authorId}")
|
||||
.queryParam("deliveryDate", "{date}")
|
||||
.build("AndroidPhone", "black", "13/04/2019"))
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13%2F04%2F2019");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallArrayQueryParamsBrackets_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("tag[]", "Snapdragon", "NFC")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?tag%5B%5D=Snapdragon&tag%5B%5D=NFC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallArrayQueryParams_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("category", "Phones", "Tablets")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?category=Phones&category=Tablets");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallArrayQueryParamsComma_thenURIMatched() {
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("category", String.join(",", "Phones", "Tablets"))
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?category=Phones,Tablets");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUriComponentEncoding_thenQueryParamsNotEscaped() {
|
||||
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL);
|
||||
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
|
||||
webClient = WebClient
|
||||
.builder()
|
||||
.uriBuilderFactory(factory)
|
||||
.baseUrl(BASE_URL)
|
||||
.exchangeFunction(exchangeFunction)
|
||||
.build();
|
||||
|
||||
webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/products/")
|
||||
.queryParam("name", "AndroidPhone")
|
||||
.queryParam("color", "black")
|
||||
.queryParam("deliveryDate", "13/04/2019")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.block();
|
||||
|
||||
verifyCalledUrl("/products/?name=AndroidPhone&color=black&deliveryDate=13/04/2019");
|
||||
}
|
||||
|
||||
private void verifyCalledUrl(String relativeUrl) {
|
||||
ClientRequest request = argumentCaptor.getValue();
|
||||
assertEquals(String.format("%s%s", BASE_URL, relativeUrl), request.url().toString());
|
||||
|
||||
verify(exchangeFunction).exchange(request);
|
||||
verifyNoMoreInteractions(exchangeFunction);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.reactive.webflux.annotation;
|
||||
|
||||
import com.baeldung.reactive.webflux.Employee;
|
||||
import com.baeldung.reactive.webflux.EmployeeRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringApplication.class)
|
||||
class EmployeeControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebTestClient testClient;
|
||||
|
||||
@MockBean
|
||||
private EmployeeRepository employeeRepository;
|
||||
|
||||
@Test
|
||||
void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
|
||||
|
||||
Employee employee = new Employee("1", "Employee 1 Name");
|
||||
|
||||
given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
|
||||
|
||||
testClient.get()
|
||||
.uri("/employees/1")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(Employee.class).isEqualTo(employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetAllEmployees_thenCorrectEmployees() {
|
||||
List<Employee> employeeList = Arrays.asList(
|
||||
new Employee("1", "Employee 1 Name"),
|
||||
new Employee("2", "Employee 2 Name"),
|
||||
new Employee("3", "Employee 3 Name")
|
||||
);
|
||||
Flux<Employee> employeeFlux = Flux.fromIterable(employeeList);
|
||||
|
||||
given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
|
||||
|
||||
testClient.get()
|
||||
.uri("/employees")
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBodyList(Employee.class).isEqualTo(employeeList);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "admin", roles = { "ADMIN" })
|
||||
void givenValidUser_whenUpdateEmployee_thenEmployeeUpdated() {
|
||||
Employee employee = new Employee("10", "Employee 10 Updated");
|
||||
|
||||
given(employeeRepository.updateEmployee(employee)).willReturn(Mono.just(employee));
|
||||
|
||||
testClient.post()
|
||||
.uri("/employees/update")
|
||||
.body(Mono.just(employee), Employee.class)
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody(Employee.class).isEqualTo(employee);
|
||||
|
||||
verify(employeeRepository).updateEmployee(employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void givenInvalidUser_whenUpdateEmployee_thenForbidden() {
|
||||
Employee employee = new Employee("10", "Employee 10 Updated");
|
||||
|
||||
testClient.post()
|
||||
.uri("/employees/update")
|
||||
.body(Mono.just(employee), Employee.class)
|
||||
.exchange()
|
||||
.expectStatus().isForbidden();
|
||||
|
||||
verifyNoInteractions(employeeRepository);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.reactive.webflux.functional;
|
||||
|
||||
import com.baeldung.reactive.webflux.Employee;
|
||||
import com.baeldung.reactive.webflux.EmployeeRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class)
|
||||
class EmployeeSpringFunctionalIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeFunctionalConfig config;
|
||||
|
||||
@MockBean
|
||||
private EmployeeRepository employeeRepository;
|
||||
|
||||
@Test
|
||||
void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() {
|
||||
WebTestClient client = WebTestClient.bindToRouterFunction(config.getEmployeeByIdRoute())
|
||||
.build();
|
||||
|
||||
Employee employee = new Employee("1", "Employee 1");
|
||||
|
||||
given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee));
|
||||
|
||||
client.get()
|
||||
.uri("/employees/1")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(Employee.class)
|
||||
.isEqualTo(employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetAllEmployees_thenCorrectEmployees() {
|
||||
WebTestClient client = WebTestClient.bindToRouterFunction(config.getAllEmployeesRoute())
|
||||
.build();
|
||||
|
||||
List<Employee> employees = Arrays.asList(new Employee("1", "Employee 1"), new Employee("2", "Employee 2"));
|
||||
|
||||
Flux<Employee> employeeFlux = Flux.fromIterable(employees);
|
||||
given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
|
||||
|
||||
client.get()
|
||||
.uri("/employees")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Employee.class)
|
||||
.isEqualTo(employees);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUpdateEmployee_thenEmployeeUpdated() {
|
||||
WebTestClient client = WebTestClient.bindToRouterFunction(config.updateEmployeeRoute())
|
||||
.build();
|
||||
|
||||
Employee employee = new Employee("1", "Employee 1 Updated");
|
||||
|
||||
client.post()
|
||||
.uri("/employees/update")
|
||||
.body(Mono.just(employee), Employee.class)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
|
||||
verify(employeeRepository).updateEmployee(employee);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<include
|
||||
resource="org/springframework/boot/logging/logback/base.xml" />
|
||||
<appender name="LISTAPPENDER"
|
||||
class="com.baeldung.reactive.debugging.consumer.utils.ListAppender">
|
||||
</appender>
|
||||
<logger
|
||||
name="com.baeldung.reactive.debugging.consumer.service.FooService">
|
||||
<appender-ref ref="LISTAPPENDER" />
|
||||
</logger>
|
||||
|
||||
<logger name="reactor.netty.http.client" level="INFO"/>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="LISTAPPENDER" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user