#1225 - Provide implementation of WebTestClientConfigurer to support hypermedia registration.

Expand reference documentation to show ways to use it directly or via Spring Boot.
This commit is contained in:
Greg Turnquist
2020-03-27 16:52:51 -05:00
parent 6c09839cca
commit 898752f0d5
6 changed files with 296 additions and 13 deletions

View File

@@ -860,7 +860,7 @@
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
<optional>true</optional>
</dependency>
<dependency>

View File

@@ -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<EntityModel<Employee>>` 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<Employee>() {}) // <4>
.consumeWith(result -> {
// assert against this EntityModel<Employee>!
});
}
}
----
<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<Employee>` 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.

View File

@@ -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<ClientCodecConfigurer> 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<HypermediaMappingInformation> 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);
}
}

View File

@@ -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<ObjectMapper> mapper,
List<HypermediaMappingInformation> hypermediaTypes) {
return new HypermediaWebTestClientConfigurer(mapper.getIfAvailable(ObjectMapper::new), hypermediaTypes);
}
@Bean
static HypermediaWebClientBeanPostProcessor webClientBeanPostProcessor(
ObjectProvider<WebClientConfigurer> configurer) {

View File

@@ -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);
}

View File

@@ -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<EntityModel<Employee>>() {}) // <3>
.consumeWith(result -> {
CollectionModel<EntityModel<Employee>> 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);
}
}
}