Testing SseEmitter ends with timeToWait error

139 views Asked by At

I'm trying to test my SSE endpoint which uses SseEmitter:

@GetMapping("/subscribe")
public SseEmitter subscribe() {
    SseEmitter sseEmitter = new SseEmitter(4000L);

    Disposable disposable = Flux.interval(Duration.ZERO, Duration.of(1, ChronoUnit.SECONDS))
            .map(e -> event().data("data" + e))
            .log()
            .subscribe(unchecked(sseEmitter::send));

    sseEmitter.onError(e -> log.error("SSE ERROR", e));

    sseEmitter.onTimeout(unchecked(() -> {
        log.info("SSE Timeout");
        sseEmitter.complete();
    }));

    sseEmitter.onCompletion(() -> {
        log.info("SSE COMPLETED");
        disposable.dispose();
    });

    return sseEmitter;
}

The test:

@ActiveProfiles("test")
@WebMvcTest(
        controllers = SseEmitterController.class
)
@AutoConfigureWebTestClient(timeout = "36000")
class SimpleSseTest {
    
    @Autowired
    private WebTestClient webTestClient;

    @Test
    void test() {

        FluxExchangeResult<String> result = webTestClient.get()
                .uri("/subscribe")
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType("text/event-stream")
                .returnResult(String.class);

        StepVerifier.create(result.getResponseBody())
                .expectNextCount(2)
                .thenCancel()
                .verify();
    }
}

But the test fails with this error:

org.springframework.web.reactive.function.client.WebClientRequestException: Async result for handler [SseEmitterController#subscribe()] was not set during the specified timeToWait=4000; nested exception is java.lang.IllegalStateException: Async result for handler [SseEmitterController#subscribe()] was not set during the specified timeToWait=4000

Does anyone know how do I to get rid of this error?

I'm using spring-boot 2.6.8

0

There are 0 answers