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

Allan Wang

06/24/2020, 12:08 AM
When testing code using coroutines, I’ve run into the following problem: • Code launched is effectively a posted runnable, and in some cases, this causes the test to fail. The way around this is with an InstantTestExecutorRule • With instant test executor rules, switching contexts can cause deadlocks. The way around this seems to be to use an Unconfined dispatcher • Using an unconfined dispatcher causes the exception “Can’t create handler inside thread … that has not called Looper.prepare()“. The solution here is to either keep the main thread or to call prepare ourselves, which doesn’t always work as something else is preparing it. Are there any guidelines towards testing code with coroutines using an instant test executor? Or is this a case where we need to apply rules on an as needed basis, as the requirements seem to differ between tests?
i

Ian Lake

06/24/2020, 12:33 AM
Do you mean the Android Arch Components'
InstantTaskExecutorRule
? Why would you need that if you're testing coroutines? The regular Coroutines testing is usually enough: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/
a

Allan Wang

06/24/2020, 12:35 AM
I will have to verify, but there were problems with certain arch components without using the instant task executor rule
g

Giorgos Neokleous

06/24/2020, 7:54 AM
I've never had such issues with coroutines in tests. Just make sure you inject your dispatcers
w

wasyl

06/24/2020, 8:06 AM
Can you give an example o a deadlock with
InstantTaskExecutorRule
? What context are used in your tests? I find it best to either test everything using instant executor/unconfined dispatcher so that tests run synchronously, or test specifically with background dispatchers but I make sure there’s no Android framework in tested classes then (or I use Robolectric)
a

Allan Wang

06/26/2020, 12:47 AM
Awaiting on a future that is not completed yet causes a deadlock.
What do you mean by injecting my dispatchers? Without adding any rules at all, it seems like
withContext
is just freezing. If I make tests unconfined, I run into the problem of having no looper in certain threads. If I can resolve the looper issue then I think unconfined without instant task may work
The test code is all under robolectric
14 Views