Compatibility with KotlinX.Datetime
Control the virtual time during tests using KotlinX.Datetime.
Builds upon the virtual time control available out-of-the-box to allow instancing clocks, setting the current time or waiting for a given time.
Example
We want to test a fictional Scheduler
implemented using KotlinX.Coroutines. The scheduler has been implemented in a way that allows to inject the clock and the coroutine context.
First, the scheduler requires access to some kind of database. We prepare the connection to avoid copy-pasting it in each test, while still ensuring each test gets its own instance.
val prepareDatabase by prepared {
Database.connect()
}
To allow writing multiple tests using the same scheduler, we also declare it as a prepared value. We can inject the database using the previous prepared value. To let the scheduler access the virtual time, we inject the virtual time clock. To ensure the scheduler can start coroutines with delay-skipping that the test waits for, we inject the foreground coroutine scope.
val prepareScheduler by prepared {
Scheduler(
database = prepareDatabase(),
clock = time.clock,
coroutineContext = foregroundScope,
)
}
Now, we can use the helper functions to set the current time and to wait until a specific time.
test("A test that uses the time") {
time.set("2023-11-08T12:00:00Z")
val scheduler = prepareScheduler()
var executed = false
scheduler.scheduleAt("2023-11-08T12:05:00Z") {
executed = true
}
time.delayUntil("2023-11-08T12:06:00Z")
executed shouldBe true
}