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

acando86

11/04/2018, 4:19 PM
Question about unit testing. Most of my android code only relies on suspend functions idiomatically, without coroutine builders, and that causes no problems with tests. The builders (mainly, withContext or sometimes launch) are primarily used only by the end consumers of my business logic (eg, the UI presenters) .. Before structured concurrency, i was used to inject from outside the coroutine contexts in the presenter constructor , so in the main application i was passing UI/IO instances of coroutine contexts say, and in the tests i was passing an instance of something suitable for tests (typically, Unconfined). Now, after structured concurrency migration, i originally made my presenters receive coroutinescope and the IO context from outside, but I’m pretty sure there’s a better way to handle this. What's the best way to translate this kind of tests to structured concurrency? How do you usually express these tests? Thank you
👍 1
z

Zach Klippenstein (he/him) [MOD]

11/04/2018, 10:20 PM
Passing in the context to the Presenter seems reasonable, assuming you’re overriding the job with one scoped to your presenter’s lifetime. Why isn’t that technique working for your tests anymore?
g

gildor

11/05/2018, 3:27 AM
The only problem for suspend function + custom dispather is Main thread dispatche, just because this dispatcher doesn’t work for unit tests (at least on Android) But I see no problem to use IO or any other general usage dispatcher, such code is still testable. You probably want to use some advance technique, like change time for delay functions you can use TestContext for this, but this in general more advance and in most cases
withContext(AnyDispatcherExceptMain)
works well
3 Views