Does anyone know a way to invoke a method that con...
# coroutines
v
Does anyone know a way to invoke a method that contains a coroutine from a Unit Test? for example calling this initialize() here from a test: https://github.com/voghDev/HelloKotlin/blob/coroutines/app/src/main/java/es/voghdev/hellokotlin/UserDetailPresenter.kt (found Tony Owen's workaround but I'd prefer another solution: https://medium.com/@tonyowen/android-kotlin-coroutines-unit-test-16e984ba35b4)
v
Thanks for the prompt response! Still getting the
Method getMainLooper in android.os.Looper not mocked
error. Will push my code in a sec
The exact Test I'm running is this one: https://github.com/voghDev/HelloKotlin/blob/coroutines2/app/src/test/kotlin/es/voghdev/hellokotlin/UserDetailPresenterTest.kt The curious thing is that the Test seems to pass if I add a little delay(30). I keep on investigating, thanks for the link
e
1. Change your
UserDetailPresenter.initialize
from
fun initialize() {  launch(CommonPool) { … } }
to
fun initialize() = launch(CommonPool) { … }
, e.g. make it return the corresponding
Job
(you’ll need to change its super-class, too) 2. Now in your test code do it like this:
Copy code
fun myTestForSomething() = runBlocking<Unit> { // this line !!! 
   …
   presenter.initialize().join() // wait for intilize job to complete!
}
Now you should not need to introduce delay
v
Thanks Roman! I've refactored it to use
launch
and
runBlocking
as you suggested. Tests seem to be passing without the delay(30); Just one more question about
launch(UI)
. Is it necessary to use it if I want to notify results in UI thread? If I uncomment lines 39, 42 to call
launch(UI)
, tests are not passing anymore https://github.com/voghDev/HelloKotlin/blob/coroutines3/app/src/main/java/es/voghdev/hellokotlin/UserDetailPresenter.kt
e
Yes. You have to do it from UI context. You can either uncomment your
launch(UI)
or replace
CommonPool
with
UI
on line 35