Video tayyorlanmoqda

SSE endpoint'ini avtomatik test bilan qanday tekshirasiz, uning javobi hech qachon tugamasa?

Ilovani RANDOM_PORT bilan ko'taraman, WebTestClient bilan text/event-stream so'rov yuboraman, javobni Flux qilib olaman va StepVerifier'da kerakli event'lar kelgach obunani bekor qilaman. Timeout shart, bo'lmasa test osilib qoladi.

📖 Javob

MockMvc bu yerda noqulay: SseEmitter async ishlaydi va javob yopilmaydi, test esa natijani kutib qoladi. Haqiqiy server va reactive client bilan ancha tabiiy chiqadi — hatto ilova Spring MVC'da bo'lsa ham. Test scope'ga spring-boot-starter-webflux va reactor-test qo'shiladi.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
class OrderStreamIT {

    @Autowired WebTestClient client;
    @Autowired OrderEvents events;

    @Test
    void pushesStatusChange() {
        Flux<ServerSentEvent<String>> stream = client.get()
                .uri("/api/orders/42/stream")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .exchange()
                .expectStatus().isOk()
                .returnResult(new ParameterizedTypeReference<ServerSentEvent<String>>() {})
                .getResponseBody();

        StepVerifier.create(stream)
                .then(() -> events.statusChanged(42, "SHIPPED"))
                .expectNextMatches(e -> "order-status".equals(e.event())
                        && e.data().contains("SHIPPED"))
                .thenCancel()
                .verify(Duration.ofSeconds(5));
    }
}

Bu yerda to'rtta nozik joy bor:

  • thenCancel() — biz oqim tugashini kutmaymiz, kerakli event kelgach ulanishni o'zimiz uzamiz. Server tomonda bu onCompletion/onError callback'larini ham sinaydi.
  • verify(Duration) — timeout. Usiz noto'g'ri event nomi testni abadiy osiltiradi.
  • Heartbeat comment'lar bo'lsa, ular ham element bo'lib keladi (data null). Ularni filter(e -> e.data() != null) bilan o'tkazib yuboring.
  • Event'ni obunadan keyin ishga tushirish kerak — then(...) aynan shu uchun. Avval publish qilib, keyin ulansangiz, event o'tib ketadi va test "ba'zan" yiqiladi.

Qayta ulanishni (Last-Event-ID) ham shunday sinash mumkin: header'ni qo'lda qo'yib so'rov yuborasiz va o'tkazib yuborilgan event'lar kelishini tekshirasiz.