Is there a way to get a virtual timestamp in a cor...
# coroutines
a
It seems like the solution I came up with might drag in debug dependencies in production code. Is there any other way to achieve this right now?
c
What kind of date library are you using? I'm using KotlinX.Datetime, but it should be the same for any other: all your services should use a user-provided
Clock
to get the current time, instead of hard-coding it. Then, at the start of your test, you can trivially create a clock that reads the virtual time.
Your proposition is not a language feature because it would force production code to depend on the fake time logic of KotlinX.Serialization, which is tight coupling with a specific test library.
e
you can inject a TimeSource:
Copy code
suspend fun doStuff(timeSource: TimeSource = TimeSource.Monotonic) {
    ...
}

// production code
doStuff()

// test code
runTest {
    doStuff(timeSource = testScheduler.timeSource)
}
a
My motivation for finding an option without DI is mostly a matter of ergonomics. Suspend functions very often aren’t in classes but in extension functions and the like. So I’d have to pass it down the chain and would need to change the signature of every function in the chain to include a Clock.
c
That's what
context
will be for, but it's not ready yet.
a
context? Do you have a link?
e
one of many things context receivers can do, but yes that's not fully baked yet
c
Currently there's a JVM only prototype, but it really is just a prototype. It does demonstrate that context receivers will be the proper way to represent dependencies, when they're here.
e
btw do you really need a Clock (absolute time) or just a TimeSource (relative time)?
c
(also thanks Ephemient, I didn't realise TimeSource was in the stdlib)
a
I only need relative time.