Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

How do you test a Flux that emits one item per hour (for example built with Flux.interval(Duration.ofHours(1)).take(3)) without the test taking three hours?

We use StepVerifier.withVirtualTime(() -> Flux.interval(Duration.ofHours(1)).take(3)), which replaces Reactor's time-based schedulers with a virtual clock that the test moves forward by hand. The Flux must be created inside the supplier lambda so that interval picks up the virtual scheduler. The script is expectSubscription().expectNoEvent(Duration.ofHours(1)).expectNext(0L).thenAwait(Duration.ofHours(2)).expectNext(1L, 2L).verifyComplete(), with expectSubscription first because expectNoEvent counts the subscription as an event; TestPublisher and PublisherProbe help with testing operators and branches.

Why this question is asked

Time-based reactive code is everywhere: polling every few minutes, retries with backoff, timeouts, rate limiting, scheduled refreshes. Testing it with real time is slow and flaky: a test that waits three hours never runs, and one that waits three seconds fails on a busy CI server. Reactor's virtual time lets such a test run in milliseconds, and interviewers ask about it because the API has two traps that catch nearly everyone the first time. In this answer, we will recap how Reactor's time operators find their clock, see the naive test fail, write the virtual time test step by step, explain both traps, and look at TestPublisher and PublisherProbe.

1A Quick Recap: Where Time Comes From in Reactor

Operators that deal with time, such as Flux.interval, delayElements, Mono.delay, timeout and retries with backoff, do not sleep. They schedule work on a Scheduler, by default Schedulers.parallel(), asking it to run a task after a given delay. The scheduler reads the clock and runs the task when its time comes.

Because time goes through a scheduler, a test can swap in a scheduler with a fake clock. reactor-test's VirtualTimeScheduler is exactly that: its clock starts at zero and only moves when the test tells it to, and when it moves, every task that has become due runs immediately.

2The Naive Test and Why It Fails

First the version that does not work in practice.

Java
@Test
void hourlyTicks_realTime() {
StepVerifier.create(Flux.interval(Duration.ofHours(1)).take(3))
.expectNext(0L, 1L, 2L)
.verifyComplete(); // waits 3 real hours (or until CI kills it)
}

The interval is scheduled on the real parallel scheduler, so the first item arrives after a real hour. Nothing is wrong with the expectations; the problem is that the test uses the real clock.

3The Virtual Time Test, Step by Step

Now the version with virtual time. Each line moves the virtual clock or checks what happened.

Java
@Test
void hourlyTicks_virtualTime() {
StepVerifier.withVirtualTime(() -> Flux.interval(Duration.ofHours(1)).take(3))
.expectSubscription() // t = 0: the subscription signal
.expectNoEvent(Duration.ofHours(1)) // t = 0 -> 1 h: nothing may happen in this hour
.expectNext(0L) // t = 1 h: first tick
.thenAwait(Duration.ofHours(2)) // t = 1 h -> 3 h: ticks 1 and 2 become due
.expectNext(1L, 2L) // emitted at 2 h and 3 h
.verifyComplete(); // take(3) completes after the third tick
}
// runs in a few milliseconds
The virtual clock during the test
Virtual timeStepSignal
0expectSubscription()onSubscribe
0 to 1 hexpectNoEvent(1 h)none allowed
1 hexpectNext(0L)onNext(0)
1 h to 3 hthenAwait(2 h)onNext(1) at 2 h, onNext(2) at 3 h
3 hexpectNext(1L, 2L), verifyComplete()onComplete from take(3)

withVirtualTime installs a VirtualTimeScheduler as the default for time operators, then calls our supplier to build the Flux. expectNoEvent(Duration.ofHours(1)) advances the clock by one hour and fails if any signal arrives during that hour; as the clock reaches one hour, the first tick becomes due and is emitted, so expectNext(0L) passes. thenAwait(Duration.ofHours(2)) advances two more hours without checking anything in between, which releases ticks 1 and 2. Finally take(3) completes the sequence. Three hours of behaviour are verified in milliseconds, and the result is deterministic.

4Trap 1: Create the Flux Inside the Supplier

withVirtualTime takes a Supplier, not a Flux, for a reason. Time operators pick their scheduler when the operator is created, by asking for Schedulers.parallel() at that moment. If we build the Flux before withVirtualTime has installed the virtual scheduler, it captures the real one.

Java
Flux<Long> ticks = Flux.interval(Duration.ofHours(1)).take(3); // created now: uses the real clock
StepVerifier.withVirtualTime(() -> ticks) // too late
.expectSubscription()
.expectNoEvent(Duration.ofHours(1))
.expectNext(0L) // never arrives in virtual time: test hangs
.thenAwait(Duration.ofHours(2))
.expectNext(1L, 2L)
.verifyComplete();

So the lambda must call the code that creates the Flux, typically our service method, such as () -> poller.ticks(). The same applies to a service that stores a Flux in a field at construction: it must be built inside the supplier, or the service must accept a Scheduler parameter that the test can supply. Passing a Scheduler explicitly is often the cleanest design for time-based code anyway.

5Trap 2: The Subscription Counts as an Event

If we drop expectSubscription() and start with expectNoEvent, the test fails immediately, at time zero. The reason is that expectNoEvent fails on any signal, and the very first signal is onSubscribe, which arrives when the StepVerifier subscribes. So we always consume the subscription first with expectSubscription(), and only then assert a quiet period. When we just want to move time without checking quietness, thenAwait does not have this problem, but it also does not catch unexpected early items, which is why expectNoEvent is the stronger check.

6TestPublisher and PublisherProbe

Two more tools from reactor-test help with other kinds of tests. TestPublisher is a publisher we drive by hand: we call next, error or complete from the test, which is ideal for testing our own operators or code that consumes a Flux, including misbehaving sources. PublisherProbe wraps a Mono or Flux and records whether it was subscribed, which is how we test which branch of a pipeline ran.

Java
PublisherProbe<User> fallback = PublisherProbe.of(Mono.just(User.guest()));
Mono<User> result = repo.find(99).switchIfEmpty(fallback.mono());
StepVerifier.create(result).expectNext(User.guest()).verifyComplete();
fallback.assertWasSubscribed(); // passes: the fallback branch ran
TestPublisher<String> source = TestPublisher.create();
StepVerifier.create(source.flux().map(String::toUpperCase))
.then(() -> source.next("a", "b").complete())
.expectNext("A", "B")
.verifyComplete(); // passes

7Follow-up questions

Does virtual time work with delayElements, timeout and retries with backoff?

Yes, because they all schedule on Reactor's time schedulers, which withVirtualTime replaces. A retry with Retry.backoff over ten minutes can be tested in milliseconds with thenAwait. It does not work for code that sleeps with Thread.sleep or uses a different clock, such as a separately configured executor.

What is the difference between thenAwait and expectNoEvent?

Both advance the virtual clock. thenAwait just moves time and lets whatever becomes due happen, to be checked by later steps. expectNoEvent moves time and fails if any signal occurs during that period, so it also proves nothing happens too early.

Why might a virtual time test hang?

Usually because the Flux was created outside the supplier and is waiting on the real clock, or because the code uses its own scheduler that is not replaced. Setting a timeout with verify(Duration.ofSeconds(5)) turns a hang into a clear failure.

8Conclusion

In this answer, we tested a Flux that emits once an hour without waiting three hours. StepVerifier.withVirtualTime installs a virtual clock, and the test advances it with expectNoEvent and thenAwait, so expectSubscription().expectNoEvent(Duration.ofHours(1)).expectNext(0L).thenAwait(Duration.ofHours(2)).expectNext(1L, 2L).verifyComplete() checks three hours of behaviour in milliseconds. We saw the two traps: the Flux must be created inside the supplier, and expectNoEvent counts the subscription as an event. We also saw TestPublisher for driving a source by hand and PublisherProbe for checking which branch was subscribed.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use virtual time. StepVerifier.withVirtualTime takes a supplier, and inside it I create the Flux, so Flux.interval of one hour with take three. withVirtualTime installs a VirtualTimeScheduler whose clock only moves when the test moves it, and time operators like interval, delay and timeout schedule on it.

Then, if they want more

The script is expectSubscription, then expectNoEvent of one hour, which advances the clock and fails if anything happens early, then expectNext 0, then thenAwait two hours, which releases the ticks at two and three hours, then expectNext 1 and 2, and verifyComplete because take three completes. That runs in milliseconds. There are two traps.

The Flux must be built inside the lambda, because operators capture their scheduler when they are created; if I build it outside, it uses the real clock and the test hangs. And I need expectSubscription before expectNoEvent, because the subscription itself is a signal and expectNoEvent would fail at time zero.

For time-based production code I also like injecting a Scheduler so tests can control it. Beyond virtual time, reactor-test has TestPublisher, which I drive by hand with next, error and complete to test operators, and PublisherProbe, which records whether a branch like a switchIfEmpty fallback was actually subscribed.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you test a Flux that emits one item per hour (for example built with...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-testing-and-ops/d31d3fbaec/