Reactive tests and cancellation
What you will learn
Reactive tests assert the sequence of signals, including demand, errors, completion and cancellation. Cancellation is a lifecycle event, not success. Resources should be released on success, failure and cancellation, and a test must have a bounded verification deadline.
- Test cancellation and invalid demand with JDK Flow.
- Plan Reactor signal tests with StepVerifier and virtual time.
- Explain subscription-local context and cleanup.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Reactor and WebFlux examples require the companion Maven project. Their predicted results are not execution evidence.
Cancel after one value
import java.util.concurrent.Flow;import java.util.concurrent.SubmissionPublisher;import java.util.ArrayList;import java.util.List;public class Main { static class Probe implements Flow.Subscriber<Integer> { Flow.Subscription subscription; final List<Integer> values = new ArrayList<>(); Throwable error; boolean complete; public void onSubscribe(Flow.Subscription s) { subscription = s; } public void onNext(Integer n) { values.add(n); } public void onError(Throwable t) { error = t; } public void onComplete() { complete = true; } } public static void main(String[] args) { var p = new Probe(); try(var pub = new SubmissionPublisher<Integer>(Runnable::run, 4)) { pub.subscribe(p); pub.submit(1); pub.submit(2); p.subscription.request(1); p.subscription.cancel(); pub.submit(3); System.out.println(p.values); } System.out.println(p.complete); }}Expected output:
[1]falseThe synchronous test cancels before requesting another item. It sees no subsequent values or completion. Asynchronous cancellation can race with signals already in flight.
Testing signals instead of sleeps
StepVerifier can start with zero demand, request batches, assert the exact values, expect completion or error, or cancel. Use verify(Duration) for a real-time deadline. withVirtualTime replaces compatible Reactor schedulers; create the publisher inside its supplier so time-dependent operators use the virtual scheduler. Virtual time does not speed up arbitrary blocking I/O. Test demand, invalid inputs, timeout, cancellation and cleanup separately.
Context and resource ownership
Reactor Context is an immutable key/value structure associated with each subscription, not a global map or necessarily a thread-local value. contextWrite enriches context visible upstream; deferContextual reads it at subscription. Use context for correlation metadata, not as a substitute for validated identity. Flux.using scopes a synchronous resource and its disposer; usingWhen supports asynchronous cleanup on terminal signals and cancellation. doFinally observes completion, error or cancellation, but asynchronous cleanup may need its own synchronization and test. In-flight work may continue after cancellation, so give dependencies their own deadlines and idempotency safeguards.
Reject zero demand
import java.util.concurrent.Flow;import java.util.concurrent.SubmissionPublisher;import java.util.ArrayList;import java.util.List;public class Main { static class Probe implements Flow.Subscriber<Integer> { Flow.Subscription subscription; final List<Integer> values = new ArrayList<>(); Throwable error; boolean complete; public void onSubscribe(Flow.Subscription s) { subscription = s; } public void onNext(Integer n) { values.add(n); } public void onError(Throwable t) { error = t; } public void onComplete() { complete = true; } } public static void main(String[] args) { var p = new Probe(); try(var pub = new SubmissionPublisher<Integer>(Runnable::run, 4)) { pub.subscribe(p); p.subscription.request(0); System.out.println(p.error instanceof IllegalArgumentException); System.out.println(p.values); } }}Expected output:
true[]A zero request violates the subscription contract, so this publisher signals IllegalArgumentException.
Test resource cleanup on cancel
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/CancelTest.java; use the companion lab README.
package lab;import java.time.Duration;import java.util.concurrent.atomic.AtomicBoolean;import org.junit.jupiter.api.Test;import reactor.core.publisher.Flux;import reactor.test.StepVerifier;import static org.junit.jupiter.api.Assertions.assertTrue;class CancelTest { @Test void releaseOnCancel() { var released = new AtomicBoolean(); var source = Flux.using(() -> released, flag -> Flux.range(1, 5), flag -> flag.set(true)); StepVerifier.create(source, 0).thenRequest(1).expectNext(1) .thenCancel().verify(Duration.ofSeconds(2)); assertTrue(released.get()); }}Predicted behavior: The first item arrives; cancellation runs the disposer.
Flux.using owns the resource for the subscription; the test checks the cleanup flag.
Test independent contexts and time
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/ContextTest.java; use the companion lab README.
package lab;import java.time.Duration;import org.junit.jupiter.api.Test;import reactor.core.publisher.Mono;import reactor.test.StepVerifier;class ContextTest { @Test void perSubscriptionContext() { Mono<String> read = Mono.deferContextual(c -> Mono.just(c.get("requestId"))); StepVerifier.create(read.contextWrite(c -> c.put("requestId", "demo-a"))) .expectNext("demo-a").expectComplete().verify(Duration.ofSeconds(2)); StepVerifier.create(read.contextWrite(c -> c.put("requestId", "demo-b"))) .expectNext("demo-b").expectComplete().verify(Duration.ofSeconds(2)); } @Test void virtualClock() { StepVerifier.withVirtualTime(() -> Mono.delay(Duration.ofSeconds(5))) .expectSubscription().expectNoEvent(Duration.ofSeconds(4)) .thenAwait(Duration.ofSeconds(1)).expectNext(0L).expectComplete() .verify(Duration.ofSeconds(2)); }}Predicted behavior: Two subscribers see distinct IDs; a five-second virtual delay emits once.
The time-sensitive publisher is constructed inside the virtual-time supplier.
Common mistakes
Do not use Thread.sleep to prove a signal has or has not happened. Do not count cancel as onComplete, assume it interrupts all remote work, or leave a verifier with an unlimited deadline. Do not use shared mutable context for unrelated requests.
Practice
Create a Flow subscriber, request two of three buffered values, cancel, and print the received list and completion flag after closing the publisher.
Expected output:
[4, 5]falseCompare with the manual review criteria.
Official reading: Flow · Subscription · Reactor · StepVerifier. Reactor and WebFlux execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reactive tests and cancellation — knowledge check
Reactive programming reasoning.
What should a test expect after cancellation?
Why use a verification timeout?
Where create a virtual-time publisher?
Where does Reactor Context belong?
What does using manage?