https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

dsgryazin

03/17/2018, 3:25 PM
Q: How to test time-dependent code with coroutines? There is a very nice
TestScheduler
in Rx, making time shifting in test a breeze. I'd expect a special
CoroutineDispatcher
for testing reasons. I've looked through the tests in
coroutines-core
repository, but did not find examples there. Moreover it's full of realtime delays
delay(100)
. The case is testing UI-sensitive code, where delays can be impermissibly long.
👍 1
e

elizarov

03/17/2018, 6:47 PM
There is one internally but nothing public/stable at the moment.
s

streetsofboston

03/18/2018, 2:00 PM
Hi, @dsgryazin and @elizarov , I wrote something like that for our projects' unit-tests: https://gist.github.com/streetsofboston/6ea225c61566e6d349883082fbb9f020
Copy code
This [CoroutineContext] dispatcher can be used to simulate virtual time to speed up
 code, especially tests, that deal with delays and timeouts.

 Specify an instance of this context when calling the *non-blocking* [kotlinx.coroutines.experimental.launch]
 or [kotlinx.coroutines.experimental.async] and then advance time or trigger the actions
 to make the co-routines execute.

 This works much like the *TestScheduler* in RxJava, which allows to speed up tests that deal
 with non-blocking Rx chains that contain delays or timeouts.

 This dispatcher can also handle *blocking* coroutines that are started by
 [kotlinx.coroutines.experimental.runBlocking]. This dispatcher's virtual time will be automatically
 advanced based based on the delayed actions within the coroutine(s).
👍 2
e

elizarov

03/18/2018, 5:34 PM
@streetsofboston If you care to contribute this implementation, PR to
kotlinx.coroutines
will be welcome.
👍 1
s

streetsofboston

03/19/2018, 8:19 PM
@elizarov Since this TestCoroutineContext is for JVM only, where in
kotlinx.coroutines
should this class be added?
e

elizarov

03/20/2018, 2:09 PM
kotlinx-coroutines-core
module is for JVM. The package does not matter much, as different modules can have slightly varying APIs in the same packages. Moreover, I don't see a big problem to port this class to other platforms in the future, too
s

streetsofboston

03/20/2018, 2:14 PM
Thanks! I’ll put it in a package with the name
test
(like the
TestScheduler
on Rx Java 2).
e

elizarov

03/20/2018, 2:14 PM
ok
s

streetsofboston

03/21/2018, 9:21 PM
3 Views