Hi everyone. If I would write this method: ```sus...
# coroutines
c
Hi everyone. If I would write this method:
Copy code
suspend fun timeDifference() : Int {
   val x = System.currentTimeMillis()
   delay(5.toDuration(DurationUnit.SECONDS)
   val y = System.currentTimeMillis()
   return TimeUnit.SECONDS.ofSecond(y - x)
}
and then write a test for this:
Copy code
@Test
fun test() = runTest {
   val result = timeDifference()
   advanceUntilIdle()
   printLn(result)
}
Is it true that the output would be inconsistent? I tried it a lot of times and it doesn’t print the “predicted result” (in this case 5 seconds) but rather some other number.
k
runTest will do some weirdness with “virtual time” within its dispatcher. Things like
delay
and
debounce
won’t reflect wall time.
b
You have to inject an abstract time provider. It will be a System.currentTimeMillis in the app, but TestScope.currentTime in tests. Then you will be able to write tests with stable results
c
thanks for the answers