diff --git a/pom.xml b/pom.xml
index 4ddc3067..f2dd6514 100644
--- a/pom.xml
+++ b/pom.xml
@@ -860,7 +860,7 @@
org.springframework
spring-test
${spring.version}
- test
+ true
diff --git a/src/main/asciidoc/client.adoc b/src/main/asciidoc/client.adoc
index 849ad67d..dcc81366 100644
--- a/src/main/asciidoc/client.adoc
+++ b/src/main/asciidoc/client.adoc
@@ -90,3 +90,60 @@ assertThat(link.getRel(), is("foo"));
assertThat(link.getHref(), is("/foo/bar"));
----
====
+
+[[client.web-test-client]]
+== Configuring `WebTestClient` Instances
+
+When working with hypermedia-enabled representations, a common task is to execute various tests using `WebTestClient`.
+
+To configure an instance of `WebTestClient` in a test case, check out this example:
+
+.Configuring `WebTestClient` when using Spring HATEOAS
+====
+[source, java, indent=0, tabsize=2]
+----
+include::{base-dir}/src/test/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurerTest.java[tag=web-test-client]
+----
+<1> Register your configuration class that uses `@EnableHypermediaSupport` to enable HAL support.
+<2> Use `HypermediaWebTestClientConfigurer` to apply hypermedia support.
+<3> Ask for a response of `CollectionModel>` using Spring HATEOAS's `TypeReferences.CollectionModelType` helper.
+<4> After getting the "body" in Spring HATEOAS format, assert against it!
+====
+
+IMPORTANT: `WebTestClient` is an immutable value type, so you can't alter it in place. `WebClientConfigurer` returns a mutated
+variant that you must then capture to use it.
+
+If you are using Spring Boot, there are additional options, like this:
+
+.Configuring `WebTestClient` when using Spring Boot
+====
+[source,java,tabsize=2]
+----
+@SpringBootTest
+@AutoConfigureWebTestClient // <1>
+class WebClientBasedTests {
+
+ @Test
+ void exampleTest(@Autowired WebTestClient.Builder builder, @Autowired HypermediaWebTestClientConfigurer configurer) { // <2>
+ client = builder.apply(configurer).build(); // <3>
+
+ client.get().uri("/") //
+ .exchange() //
+ .expectBody(new TypeReferences.EntityModelType() {}) // <4>
+ .consumeWith(result -> {
+ // assert against this EntityModel!
+ });
+ }
+}
+----
+<1> This is Spring Boot's test annotation that will configure a `WebTestClient.Builder` for this test class.
+<2> Autowire Spring Boot's `WebTestClient.Builder` into `builder` and Spring HATEOAS's configurer as method parameters.
+<3> Use `HypermediaWebTestClientConfigurer` to register support for hypermedia.
+<4> Signal you want an `EntityModel` returned using `TypeReferences`.
+
+Again, you can use similar assertions as the earlier example.
+====
+
+There are many other ways to fashion test cases. `WebTestClient` can be bound to controllers, functions, and URLs. This section isn't meant to show all that. Instead, this gives you some examples to get started. The important thing is that by applying `HypermediaWebTestClientConfigurer`, any instance of `WebTestClient` can be altered to handle hypermedia.
+
+
diff --git a/src/main/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurer.java b/src/main/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurer.java
new file mode 100644
index 00000000..4e0038ec
--- /dev/null
+++ b/src/main/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurer.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2019-2020 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.hateoas.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.http.client.reactive.ClientHttpConnector;
+import org.springframework.http.codec.ClientCodecConfigurer;
+import org.springframework.http.codec.json.Jackson2JsonDecoder;
+import org.springframework.http.codec.json.Jackson2JsonEncoder;
+import org.springframework.test.web.reactive.server.MockServerConfigurer;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.test.web.reactive.server.WebTestClientConfigurer;
+import org.springframework.util.Assert;
+import org.springframework.util.MimeType;
+import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Assembles {@link Jackson2JsonEncoder}s and {@link Jackson2JsonDecoder}s needed to wire a {@link WebTestClient} with
+ * hypermedia support.
+ *
+ * @author Greg Turnquist
+ * @since 1.1
+ */
+public class HypermediaWebTestClientConfigurer implements WebTestClientConfigurer, MockServerConfigurer {
+
+ private Consumer configurer;
+
+ /**
+ * Creates a new {@link HypermediaWebTestClientConfigurer} for the given {@link ObjectMapper} and
+ * {@link HypermediaMappingInformation}s.
+ *
+ * @param mapper must not be {@literal null}.
+ * @param hypermediaTypes must not be {@literal null}.
+ */
+ HypermediaWebTestClientConfigurer(ObjectMapper mapper, List hypermediaTypes) {
+
+ Assert.notNull(mapper, "mapper must not be null!");
+ Assert.notNull(hypermediaTypes, "hypermediaTypes must not be null!");
+
+ this.configurer = clientCodecConfigurer -> hypermediaTypes.forEach(hypermediaType -> {
+
+ ObjectMapper objectMapper = hypermediaType.configureObjectMapper(mapper.copy());
+ MimeType[] mimeTypes = hypermediaType.getMediaTypes().toArray(new MimeType[0]);
+
+ clientCodecConfigurer.customCodecs().registerWithDefaultConfig(new Jackson2JsonEncoder(objectMapper, mimeTypes));
+ clientCodecConfigurer.customCodecs().registerWithDefaultConfig(new Jackson2JsonDecoder(objectMapper, mimeTypes));
+ });
+ }
+
+ /**
+ * Register the proper {@link Jackson2JsonEncoder}s and {@link Jackson2JsonDecoder}s for a given
+ * {@link WebTestClient}.
+ */
+ @Override
+ public void afterConfigurerAdded(WebTestClient.Builder builder, WebHttpHandlerBuilder webHttpHandlerBuilder,
+ ClientHttpConnector clientHttpConnector) {
+ builder.codecs(this.configurer);
+ }
+}
diff --git a/src/main/java/org/springframework/hateoas/config/WebClientHateoasConfiguration.java b/src/main/java/org/springframework/hateoas/config/WebClientHateoasConfiguration.java
index 67b65e5d..16124f80 100644
--- a/src/main/java/org/springframework/hateoas/config/WebClientHateoasConfiguration.java
+++ b/src/main/java/org/springframework/hateoas/config/WebClientHateoasConfiguration.java
@@ -15,19 +15,18 @@
*/
package org.springframework.hateoas.config;
+import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
-
-import java.util.List;
-
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Lazy;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.function.client.WebClient;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.List;
/**
* Spring WebFlux HATEOAS configuration.
@@ -44,6 +43,13 @@ class WebClientHateoasConfiguration {
return new WebClientConfigurer(mapper.getIfAvailable(ObjectMapper::new), hypermediaTypes);
}
+ @Bean
+ @Lazy
+ HypermediaWebTestClientConfigurer webTestClientConfigurer(ObjectProvider mapper,
+ List hypermediaTypes) {
+ return new HypermediaWebTestClientConfigurer(mapper.getIfAvailable(ObjectMapper::new), hypermediaTypes);
+ }
+
@Bean
static HypermediaWebClientBeanPostProcessor webClientBeanPostProcessor(
ObjectProvider configurer) {
diff --git a/src/test/java/org/springframework/hateoas/ArchitectureTest.java b/src/test/java/org/springframework/hateoas/ArchitectureTest.java
index e577f413..e2ab4b63 100644
--- a/src/test/java/org/springframework/hateoas/ArchitectureTest.java
+++ b/src/test/java/org/springframework/hateoas/ArchitectureTest.java
@@ -15,14 +15,6 @@
*/
package org.springframework.hateoas;
-import static com.tngtech.archunit.core.domain.JavaClass.Predicates.*;
-import static org.springframework.hateoas.ArchitectureTest.Architecture.*;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestInstance;
-import org.junit.jupiter.api.TestInstance.Lifecycle;
-import org.springframework.lang.Nullable;
-
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.Dependency;
import com.tngtech.archunit.core.domain.JavaClass;
@@ -33,6 +25,13 @@ import com.tngtech.archunit.core.importer.ImportOptions;
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition;
import com.tngtech.archunit.library.dependencies.SliceRule;
import com.tngtech.archunit.library.dependencies.SlicesRuleDefinition;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.springframework.lang.Nullable;
+
+import static com.tngtech.archunit.core.domain.JavaClass.Predicates.*;
+import static org.springframework.hateoas.ArchitectureTest.Architecture.*;
/**
* Tests to verify certain architectural assumptions.
@@ -69,6 +68,7 @@ class ArchitectureTest {
.and().resideOutsideOfPackages("..reactive") //
.and().haveSimpleNameNotStartingWith("WebFlux") //
.and().haveSimpleNameNotStartingWith("WebClient") //
+ .and().haveSimpleNameNotStartingWith("HypermediaWebTestClient") //
.should().dependOnClassesThat(areSpringFrameworkClassesWithReactiveDependency) //
.check(classes);
}
diff --git a/src/test/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurerTest.java b/src/test/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurerTest.java
new file mode 100644
index 00000000..4341fa16
--- /dev/null
+++ b/src/test/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurerTest.java
@@ -0,0 +1,145 @@
+package org.springframework.hateoas.config;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.hateoas.CollectionModel;
+import org.springframework.hateoas.EntityModel;
+import org.springframework.hateoas.IanaLinkRelations;
+import org.springframework.hateoas.Link;
+import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
+import org.springframework.hateoas.server.core.TypeReferences;
+import org.springframework.hateoas.support.Employee;
+import org.springframework.hateoas.support.WebFluxEmployeeController;
+import org.springframework.http.MediaType;
+import org.springframework.http.codec.HttpMessageReader;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.web.reactive.function.client.ExchangeStrategies;
+import org.springframework.web.reactive.function.client.WebClient;
+
+import java.util.Collections;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.springframework.hateoas.MediaTypes.*;
+import static org.springframework.hateoas.support.ContextTester.*;
+
+public class HypermediaWebTestClientConfigurerTest {
+
+ private static MediaType FRODO_JSON = MediaType.parseMediaType("application/frodo+json");
+
+ @Test // #1225
+ void webTestClientConfigurerHandlesSingleHypermediaType() {
+
+ withContext(HalConfig.class, context -> {
+
+ HypermediaWebTestClientConfigurer configurer = context.getBean(HypermediaWebTestClientConfigurer.class);
+
+ WebTestClient webTestClient = WebTestClient.bindToServer().apply(configurer).build();
+
+ assertThat(exchangeStrategies(webTestClient).messageReaders())
+ .flatExtracting(HttpMessageReader::getReadableMediaTypes) //
+ .contains(HAL_JSON) //
+ .doesNotContain(HAL_FORMS_JSON, COLLECTION_JSON, UBER_JSON);
+ });
+ }
+
+ @Test // #1225
+ void webTestClientConfigurerHandlesAllHypermediaTypes() {
+
+ withContext(AllHypermediaConfig.class, context -> {
+
+ HypermediaWebTestClientConfigurer configurer = context.getBean(HypermediaWebTestClientConfigurer.class);
+
+ WebTestClient webTestClient = WebTestClient.bindToServer().apply(configurer).build();
+
+ assertThat(exchangeStrategies(webTestClient).messageReaders())
+ .flatExtracting(HttpMessageReader::getReadableMediaTypes) //
+ .contains(HAL_JSON, HAL_FORMS_JSON, COLLECTION_JSON, UBER_JSON);
+ });
+ }
+
+ @Test // #1225
+ void webTestClientConfigurerHandlesCustomHypermediaTypes() {
+
+ withContext(CustomHypermediaConfig.class, context -> {
+
+ HypermediaWebTestClientConfigurer configurer = context.getBean(HypermediaWebTestClientConfigurer.class);
+
+ WebTestClient webTestClient = WebTestClient.bindToServer().apply(configurer).build();
+
+ assertThat(exchangeStrategies(webTestClient).messageReaders())
+ .flatExtracting(HttpMessageReader::getReadableMediaTypes) //
+ .contains(HAL_JSON, FRODO_JSON) //
+ .doesNotContain(HAL_FORMS_JSON, COLLECTION_JSON, UBER_JSON);
+ });
+ }
+
+ // tag::web-test-client[]
+ @Test // #1225
+ void webTestClientShouldSupportHypermediaDeserialization() {
+
+ // Configure an application context programmatically.
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
+ context.register(HalConfig.class); // <1>
+ context.refresh();
+
+ // Create an instance of a controller for testing
+ WebFluxEmployeeController controller = new WebFluxEmployeeController();
+ controller.reset();
+
+ // Extract the WebTestClientConfigurer from the app context.
+ HypermediaWebTestClientConfigurer configurer = context.getBean(HypermediaWebTestClientConfigurer.class);
+
+ // Create a WebTestClient by binding to the controller and applying the hypermedia configurer.
+ WebTestClient client = WebTestClient.bindToController(controller).apply(configurer).build(); // <2>
+
+ // Exercise the controller.
+ client.get().uri("http://localhost/employees") //
+ .exchange() //
+ .expectStatus().isOk() //
+ .expectBody(new TypeReferences.CollectionModelType>() {}) // <3>
+ .consumeWith(result -> {
+ CollectionModel> model = result.getResponseBody(); // <4>
+
+ // Assert against the hypermedia model.
+ assertThat(model.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(Link.of("/employees"));
+ assertThat(model.getContent()).hasSize(2);
+ });
+ }
+ // end::web-test-client[]
+
+ /**
+ * Extract the {@link ExchangeStrategies} from a {@link WebTestClient} to assert it has the proper message readers and
+ * writers.
+ *
+ * @param webTestClient
+ * @return
+ */
+ private static ExchangeStrategies exchangeStrategies(WebTestClient webTestClient) {
+
+ WebClient webClient = (WebClient) ReflectionTestUtils.getField(webTestClient, "webClient");
+
+ return (ExchangeStrategies) ReflectionTestUtils
+ .getField(ReflectionTestUtils.getField(webClient, "exchangeFunction"), "strategies");
+ }
+
+ @EnableHypermediaSupport(type = HypermediaType.HAL)
+ static class HalConfig {
+
+ }
+
+ @EnableHypermediaSupport(
+ type = { HypermediaType.HAL, HypermediaType.HAL_FORMS, HypermediaType.COLLECTION_JSON, HypermediaType.UBER })
+ static class AllHypermediaConfig {
+
+ }
+
+ static class CustomHypermediaConfig extends HalConfig {
+
+ @Bean
+ HypermediaMappingInformation hypermediaMappingInformation() {
+ return () -> Collections.singletonList(FRODO_JSON);
+ }
+ }
+}