|
1 | 1 | [[spring-mvc-test-vs-streaming-response]] |
2 | 2 | = Streaming Responses |
3 | 3 |
|
4 | | -The best way to test streaming responses such as Server-Sent Events is through the |
5 | | -<<WebTestClient>> which can be used as a test client to connect to a `MockMvc` instance |
6 | | -to perform tests on Spring MVC controllers without a running server. For example: |
7 | | - |
8 | | -[tabs] |
9 | | -====== |
10 | | -Java:: |
11 | | -+ |
12 | | -[source,java,indent=0,subs="verbatim,quotes",role="primary"] |
13 | | ----- |
14 | | - WebTestClient client = MockMvcWebTestClient.bindToController(new SseController()).build(); |
15 | | -
|
16 | | - FluxExchangeResult<Person> exchangeResult = client.get() |
17 | | - .uri("/persons") |
18 | | - .exchange() |
19 | | - .expectStatus().isOk() |
20 | | - .expectHeader().contentType("text/event-stream") |
21 | | - .returnResult(Person.class); |
22 | | -
|
23 | | - // Use StepVerifier from Project Reactor to test the streaming response |
24 | | -
|
25 | | - StepVerifier.create(exchangeResult.getResponseBody()) |
26 | | - .expectNext(new Person("N0"), new Person("N1"), new Person("N2")) |
27 | | - .expectNextCount(4) |
28 | | - .consumeNextWith(person -> assertThat(person.getName()).endsWith("7")) |
29 | | - .thenCancel() |
30 | | - .verify(); |
31 | | ----- |
32 | | -====== |
33 | | - |
34 | | -`WebTestClient` can also connect to a live server and perform full end-to-end integration |
35 | | -tests. This is also supported in Spring Boot where you can |
36 | | -{docs-spring-boot}/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-with-running-server[test a running server]. |
37 | | - |
| 4 | +You can use `WebTestClient` to test xref:testing/webtestclient.adoc#webtestclient-stream[streaming responses] |
| 5 | +such as Server-Sent Events. However, `MockMvcWebTestClient` doesn't support infinite |
| 6 | +streams because there is no way to cancel the server stream from the client side. |
| 7 | +To test infinite streams, you'll need to |
| 8 | +xref:testing/webtestclient.adoc#webtestclient-server-config[bind to] a running server, |
| 9 | +or when using Spring Boot, |
| 10 | +{docs-spring-boot}/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-with-running-server[test with a running server]. |
| 11 | + |
| 12 | +`MockMvcWebTestClient` does support asynchronous responses, and even streaming responses. |
| 13 | +The limitation is that it can't influence the server to stop, and therefore the server |
| 14 | +must finish writing the response on its own. |
38 | 15 |
|
0 commit comments