ExchangeFunction is the Spring WebFlux abstraction for asynchronously turning an HTTP request into an HTTP response. WebClient and WebTestClient both wrap it, while adding different capabilities: production features for WebClient and request capture and assertions for WebTestClient. section 4.2.2
Use the abstraction to understand how WebFlux clients connect to application handlers or real servers:
- With @AutoConfigureWebTestClient, WebTestClient adapts its ExchangeFunction to call the application’s HttpHandler directly without starting a web server or traversing the Netty stack. section 4.2.2
- WebTestClient can instead wrap an ExchangeFunction configured for real HTTP requests, using a complete URL and a server-backed client. section 4.2.2
- Test methods may call exchange() synchronously because WebTestClient internally blocks with a timeout, despite the underlying reactive abstraction. section 4.2.2
Listing 4.10 A WebTestClient-based test
@SpringBootTest
@AutoConfigureWebTestClient #1
class ApiWebClientTests {
@Autowired
private WebTestClient client; #2
@Test
void indexPageHasSelectedCity() {
selectCity("Paris");
client.get()
.uri("/")
.exchange() #3
.expectStatus() #4
.isOk() #4
.expectBody(String.class) #4
.value(body -> #4
assertThat(body).contains("Paris (France)") #4
);
}
}
Shows WebTestClient invoking exchange(), asserting the response status, and inspecting the response body in an application-context test. section 4.2.2
