I still haven't managed to verify that a suspendin...
# coroutines
c
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
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
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
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
Bingo!
runBlocking(testCoroutineContext)
did the trick.
s
@curioustechizen Did you try to pass
Dispatchers.Unconfined
instead of the
testCoroutineContext
?
c
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
No problem, glad it worked out!
s
@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
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
Hmmm… did you try
EmptyCoroutineContext
?
c
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
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
@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