Does the library offer some way to run tests with ...
# kotlinx-datetime
s
Does the library offer some way to run tests with a test instance of the
Clock
interface? Basically one where I can control the time passed myself. Basically I’m trying to run a test where two classes receive a Clock instance, current just passing in Clock.System in, but then
now()
resolves two different times but I want for the test for them to resolve on the same now. I can probably make my own Clock instance where I just always return the same Instance, but just checking if there’s some existing artifact which gives a nice test Clock instance with some more control than what I’d do myself.
d
Nothing official is provided, but this probably should be fairly straightforward to implement, no?
Copy code
public class TestClock: Clock {
    private var now: Instant = Clock.System.now()

    public fun advanceTimeBy(duration: Duration) {
        require(duration > Duration.ZERO)
        now += duration
    }

    override fun now(): Instant = now
}
s
Yeap this is pretty much what I had written myself too (minus the require step, which is smart 😅) I was simply wondering if there was something somewhere that I missed, but I understand why there’s not atm. Thanks for the help 🤗
h
Alternative if you want to sync your clock with
runTest
and its `testTimeSource`:
Copy code
@ExperimentalTime
 public fun TimeSource.toClock(offset: Instant = Instant.fromEpochSeconds(0)): Clock = object : Clock {
     private val startMark: TimeMark = markNow()
     override fun now() = offset + startMark.elapsedNow()
 }
s
Ohh interesting yeah I might need that in the future, thanks!