Testing Reactor
Specialized testing utilities for verifying reactive streams.
StepVerifier Basics
Section titled “StepVerifier Basics”@Testvoid testFlux() { Flux<String> flux = Flux.just("foo", "bar");
StepVerifier.create(flux) .expectNext("foo") // Verify next element .expectNextCount(1) // Verify count of elements .expectComplete() // Verify completion .verify(Duration.ofSeconds(5));}
@Testvoid testError() { Flux<String> flux = Flux.error(new RuntimeException());
StepVerifier.create(flux) .expectError(RuntimeException.class) .verify();}Advanced Testing
Section titled “Advanced Testing”// Virtual time testing@Testvoid testVirtualTime() { StepVerifier.withVirtualTime(() -> Flux.interval(Duration.ofHours(1)).take(2) ) .expectSubscription() .thenAwait(Duration.ofHours(2)) // Skip 2 hours instantly .expectNext(0L, 1L) .verifyComplete();}
// Context testing@Testvoid testContext() { Mono<String> mono = Mono.deferContextual(ctx -> Mono.just("Hello " + ctx.get("user")) );
StepVerifier.create(mono.contextWrite(ctx -> ctx.put("user", "Alice"))) .expectNext("Hello Alice") .verifyComplete();}Test Support Utilities
Section titled “Test Support Utilities”// TestPublisher for controlled testingTestPublisher<String> testPublisher = TestPublisher.create();Flux<String> testFlux = testPublisher.flux();
StepVerifier.create(testFlux) .then(() -> testPublisher.next("a", "b")) .expectNext("a", "b") .then(() -> testPublisher.error(new RuntimeException())) .expectError();