If I can't use the SystemClock in my unit tests, t...
# coroutines
f
If I can't use the SystemClock in my unit tests, then what's the point of the time value in
advanceTimeBy
? For example, I'm using a fake timesource so the actual advanced time doesn't matter.
h
What do you mean? This?
Copy code
runTest {
  advanceTimeBy(1.minutes)
}
f
yes
I need to use it to execute code but the actual value in there doesn't seem to matter
because the time is coming from my fake time source
h
Are you using
TestScope
with another TimeSource, not the provided one?
This is the idea using the provided `testTimeSource`:
Copy code
@Test
@ExperimentalTime
fun testAdvanceTimeSource() = runTest {
    val expected = 1.seconds
    val actual = testTimeSource.measureTime {
        delay(expected) // or advanceTimeBy(1.seconds)
    }
    assertEquals(expected, actual)
}
f
What exactly is
timeSource
? I don't have that available in my code
False alarm, I have it available. I didn't know about this, thank you! So I should use this instead of my own fake time source, right?
This doesn't seem to be mentioned in the
kotlinx-coroutines-test
documentation. Where do I learn about this stuff?
But how do I use this in my own classes? I wanna uses the `SystemClock`'s
elapsedRealtime
in my production code.
h
Yes, you should/could use this timeSource 🙂 What is SystemClock?
f
oh SystemClock is an Android class
Should I wrap this in my own TimeSource interface?
I'm using the SystemClock's time to make my countdown timer exact (delay itself isn't). Is Kotlin's TimeSource exact?
When I use TimeSource.Monotonic on Android I'm always getting 0 for
elapsedNow
h
First: TimeSource is not a Clock. TimeSource.Monotonic is only usable for jobs with keeping your system active. Its behavior is not defined when your computer sleeps or it does not support NTP update. See details here: https://github.com/Kotlin/kotlinx-datetime/pull/164#issuecomment-997859203 Oh, SystemClock is a final class without an interface... How do you mock it at all? For tests!!!, you increase the timesource by your own. So you are safe to write some kind:
TimeSource.toTestSystemClock()
. In tests,
delay
is exact.
f
i need an exact time source in my production code so the timer works
that's why I use Android's SystemClock for reference
But in my tests the time is coming from my own fake time source wrapper
it's just that the `TestScope`'s time doesn't really mean anything anymore
it just has to be enough to skip delays
h
but how do you mock SystemClock?
f
I have a wrapper that uses the SystemClock in real code and a Long value in the tests
in the fake on I have an advance-time method that i use to increase that Long
h
Okay, if you already use
Long
, what prevents you from using
TestScope.currentTime
? 😄
f
I don't know what to use in my production code
Especially since i need an exact reference point to avoid that the timer becomes imprecise