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

ashdavies

09/17/2018, 7:53 AM
Is there an idiomatic way to override the default dispatcher for unit tests? or would this be considered bad practice, and typical injection preferred?
g

gildor

09/17/2018, 8:04 AM
What is your use case for this? You can specify amount of threads for default dispathcer, but there is no way to completely replace it (except reflections), usually it shouldn’t be a problem for unit tests if you just use suspend functions and test them or just have access to Job
a

ashdavies

09/17/2018, 8:14 AM
It’s only when unit testing classes that construct a coroutine consuming suspended functions, it needs to provided with a dispatcher or scope via constructor injection which can be changed under test.
Most samples hard code
Dispatchers.main
, which made me wonder if there was an alternative without using hacky methods
s

spand

09/17/2018, 8:41 AM
I treat it as any other static dependency and pass it in.
g

gildor

09/17/2018, 8:48 AM
For UI dispatcher you always should provide it
or use own dispather that allows to switch implementation for UI
It’s the same for non-coroutine code
In general it’s good style to use suspend functions or use launch/async but always return Job, so you can test such function easily
💯 2
a

ashdavies

09/17/2018, 8:59 AM
Yep, I figured as much, I just thought I’d ask 👍
2 Views