ManualClock

class ManualClock(val start: Instant = Instant.fromEpochMilliseconds(0)) : Clock, TimeSource.WithComparableMarks(source)

A clock whose time moves only when a test calls advanceBy or advanceTo.

Inject it wherever code reads the time or sleeps through an abstraction you own, to make debouncing, retries, and expiry deterministic. It is a Clock (wall time starting at start), a TimeSource.WithComparableMarks (monotonic marks), and a millisecond source through currentTimeMillis, for code that takes clockMs: () -> Long.

Advancing resumes every sleeper whose deadline has been reached, in deadline order. Start the code under test, wait for it to suspend with waitForSleepers, then advance: advancing before a sleep registers does not wake it later. Each advance moves time directly to its target, so a coroutine that wakes and sleeps again measures its next deadline from the new time.

For code that uses delay directly, prefer runTest and its virtual time instead.

Parameters

start

The wall-clock instant reported before any advance.

Constructors

Link copied to clipboard
constructor(start: Instant = Instant.fromEpochMilliseconds(0))

Properties

Link copied to clipboard

The manual time elapsed since start.

Link copied to clipboard

The number of coroutines currently suspended in sleep or sleepUntil.

Link copied to clipboard

Functions

Link copied to clipboard
fun advanceBy(duration: Duration)

Advances manual time and resumes every sleeper whose deadline has been reached.

Link copied to clipboard
fun advanceTo(elapsed: Duration)

Moves manual time to elapsed and resumes sleepers due at or before it.

Link copied to clipboard

Returns the current wall-clock time in epoch milliseconds.

Link copied to clipboard
open override fun markNow(): ComparableTimeMark

Returns a mark at the current manual time.

Link copied to clipboard
open override fun now(): Instant

Returns start plus the manual time elapsed so far.

Link copied to clipboard
suspend fun sleep(duration: Duration)

Suspends until duration of manual time has passed.

Link copied to clipboard
suspend fun sleepUntil(deadline: Duration)

Suspends until elapsed reaches deadline.

Link copied to clipboard
suspend fun waitForSleepers(count: Int, timeout: Duration = 2.seconds)

Waits in real time until at least count coroutines are sleeping on this clock.