I'm doing ```System.currentTimeMillis() advanceTim...
# coroutines
c
I'm doing
Copy code
System.currentTimeMillis()
advanceTimeBy(1.minutes)
System.currentTimeMillis()
but the difference isn't 1 minute. How do you all recommend advancing time so that the System time that is grabbed actually advances?
p
I don’t think
advanceTimeBy(1.minutes)
has any effect on the System time. It affects the test scheduler time which is a different time counter. You have to read the time from the test scheduler.
☝️ 1
c
So System.currentTimeMillis() is actually happening in the class I'm testing. For example, I'm doing something closer to
Copy code
ClassUnderTest.markTimestamp()
advanceTimeBy(1.minutes)
ClassUnderTest.markTimestamp()
assertThat(ClassUnderTest...
Maybe my issue is that my markTimestamp() method shouldn't call System.currentTimeMillis. Maybe I can inject something else in there instead? I'll take any recs. 😅
p
I always do that, never access System.miliseconds directly, instead have an interface that returns the milliseconds. In production use System.miliseconds in test your custom implementation.
🦜 1
☝️ 5
c
Code should never use any of the
System.currentTime
functions! Production code should access time from a provided clock (via your DI technique of choice), so your tests can control how time passes. Otherwise, it's almost impossible to detect bugs that only happen in specific cases (e.g. bugs that happen the last minute before a day change). If you use KotlinX.Datetime, here's how you can create a clock from the test time: https://gitlab.com/opensavvy/pedestal/-/blob/main/cache/src/commonTest/kotlin/TestClock.kt?ref_type=heads If you use some other datetime library, there most likely is a similar concept you can implement in a similar manner
👍 1
s
If you just need to measure a time interval, use a TimeSource. In the production code, use
TimeSource.Monotonic
. In the test code, use the test coroutine scope's testTimeSource.
5
You can't get the actual clock time from a TimeSource, though; it only does intervals.
c
Thank you! A bunch of TILs for me. I've got some reading to do!
@CLOVIS that test clock was exactly what i needed. THANK YOU
c
I wish it was provided out-of-the-box, but kotlinx-coroutines-test don't want to depend on kotlinx-datetime, and vice versa, so for now we have to add it ourselves
K 1
232 Views