spring-framework: WebTestClient gets stuck on exchange when asserting infinite flux

Affects: 6.0.8

Problem:

When trying to assert a controller-method returning an infinite flux of server-sent-events, WebTestClient gets stuck on exchange.

Expected behaviour: StepVerifier asserts first three items, then cancels the subscription, test finishes successfully. Actual behaviour: WebTestClient gets stuck on exchange - expectStatus is never executed, test never finishes.

Example:

@RestController
class TestController {

    @GetMapping(path = "/test", produces = TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Long>> controllerMethod() {
            return Flux.interval(Duration.ofMillis(100))
                    .map(i -> ServerSentEvent.builder(i).build());
    }
}
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureWebTestClient
class DeviceControllerApiTest {

    @Autowired private WebTestClient webClient;

    @Test
    void testStream() {
        Flux<Long> result = webClient.get()
                .uri("/test")
                .exchange()
                .expectStatus().isOk()
                .returnResult(Long.class)
                .getResponseBody();

        StepVerifier.create(result)
                .expectNextSequence(List.of(0L, 1L, 2L))
                .thenCancel()
                .verify(Duration.ofMillis(400));
    }
}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 21 (6 by maintainers)

Most upvoted comments

There are two things.

In the referenced example, you don’t actually emit any events at all, but generally for an infinite stream, the server does not complete the response on its own. You need to do so from the client side after consuming events that you are interested in with StepVerifier. See for example this test, which reads 5 events and then cancels. That in turn closes the connection to the server.

For the specific scenario you mention where you need to start the stream, then make a separate HTTP post, WebTestClient itself is synchronous for convenience as a testing API. Therefore it blocks the main thread, and you cannot make a separate HTTP POST. You could do that asynchronously without much extra effort. For example, rewriting the above referenced test:

@Test
void entityStream() {
	Flux<Person> personFlux = Flux.defer(() ->
					this.client.get()
							.accept(TEXT_EVENT_STREAM)
							.exchange()
							.expectStatus().isOk()
							.expectHeader().contentTypeCompatibleWith(TEXT_EVENT_STREAM)
							.returnResult(Person.class)
							.getResponseBody()
			)
			.subscribeOn(Schedulers.boundedElastic());

	StepVerifier.create(personFlux)
			.then(() -> {
				// Make HTTP Post
			})
			.expectNext(new Person("N0"), new Person("N1"), new Person("N2"))
			.expectNextCount(4)
			.consumeNextWith(person -> assertThat(person.getName()).endsWith("7"))
			.thenCancel()
			.verify();
}

That said, as a scenario with multiple HTTP calls, perhaps WebClient is a good fit.