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

curioustechizen

01/30/2019, 3:34 PM
I still haven't managed to verify that a suspending function is called in tests. I created a minimal project demonstrating the problem on GitHub - https://github.com/curioustechizen/kotlin-coroutines-test-issue If anyone has any ideas please let me know.
a

ansman

01/30/2019, 3:42 PM
You’re using different contexts for
runBlocking
(you create a new one) and your view model. If you do
runBlocking(viewModel)
it might work
c

curioustechizen

01/30/2019, 3:43 PM
Hmm .. I though that's how you're supposed to inject coroutineContexts so that you can have a different one for tests?
ah no wait .. I know what you mean
a

ansman

01/30/2019, 3:44 PM
Well yeah, but you need to use the same context as the view model in
runBlocking
Try extracting your
TestCoroutineContext
into a property and pass that to
runBlocking
👍 1
c

curioustechizen

01/30/2019, 3:51 PM
Bingo!
runBlocking(testCoroutineContext)
did the trick.
s

streetsofboston

01/30/2019, 3:53 PM
@curioustechizen Did you try to pass
Dispatchers.Unconfined
instead of the
testCoroutineContext
?
c

curioustechizen

01/30/2019, 3:55 PM
Nope - just
TestCoroutineContext
In my real app there is no
delay
- instead our suspend function wraps an existing callback-based API. It looks like this solution of using the same context for
runBlocking
as in the
viewModel
is the right solution in that case
Thansks @ansman
a

ansman

01/30/2019, 3:57 PM
No problem, glad it worked out!
s

streetsofboston

01/30/2019, 4:04 PM
@curioustechizen I’m a little surprised you need to use a
TestCoroutineContext
in your test-case instead of a plain `Dispatchers.Unconfined`…. I wrote the
TestCoroutineContext
class. The class is not very useful when you don’t need to call
triggerActions
,
advanceTimeBy
or
advanceTimeTo
on it.
c

curioustechizen

01/30/2019, 4:06 PM
I did try with
Dispatchers.Unconfined
but ran into some nullability exception. I guess if I spend some more time on it I can figure out how to use it too.
s

streetsofboston

01/30/2019, 4:08 PM
Hmmm… did you try
EmptyCoroutineContext
?
c

curioustechizen

01/30/2019, 4:29 PM
Hmm .. with
EmptyCoroutineContext
I also have the test failing. It doesn't make sense to me because the way I understand it - everything should work as long as the same coroutine context is shared
s

streetsofboston

01/30/2019, 4:33 PM
Exactly…! Well, if
TestCoroutineContext
works, that’s great! 🙂 I would love to know why, though. It probably has something to do with the internal Dispatcher of the TestCoroutineContext, but the Unconfined or EmptyCoroutineContext should have similar behavior…..
c

curioustechizen

01/31/2019, 8:23 AM
@streetsofboston thanks a bunch for looking into this. For now I've used
TestCoroutineContext
and updated the github repo. I'll leave it there in case anyone wants to take a look, or try to dig into ways to achieve it using
Unconfined
or
EmptyCorutineContext
4 Views