Q: How to test time-dependent code with coroutines...
# coroutines
d
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
There is one internally but nothing public/stable at the moment.
s
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
@streetsofboston If you care to contribute this implementation, PR to
kotlinx.coroutines
will be welcome.
👍 1
s
@elizarov Since this TestCoroutineContext is for JVM only, where in
kotlinx.coroutines
should this class be added?
e
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
Thanks! I’ll put it in a package with the name
test
(like the
TestScheduler
on Rx Java 2).
e
ok
s