0

I am writing some mess around code to try and test coroutines and flows in Android. Following a common pattern I wrote a coroutine rule for handling the dispatcher and setting the main thread:

class CoroutineScopeRule(
    val dispatcher: TestDispatcher = StandardTestDispatcher(),
): TestWatcher() {

    var dispatcherProvider: CoroutineDispatcherProvider
    var sharingStrategyProvider: SharingStrategyProvider

    init {
        dispatcherProvider = CoroutineDispatcherProvider(
            main = dispatcher,
            default = dispatcher,
            io = dispatcher
        )
        sharingStrategyProvider = SharingStrategyProvider(
            lazily = SharingStarted.Lazily,
            eagerly = SharingStarted.Lazily,
            whileSubscribed = SharingStarted.Lazily
        )
    }

    override fun starting(description: Description) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description) {
        super.finished(description)
        Dispatchers.resetMain()
    }
}

Now the problem is when I try inheriting a class that sets up this rule vs delegation one.

For the inheritance I have a simple base class:

open class BaseTest {
    @get:Rule
    val coroutineScopeRule = CoroutineScopeRule()
}

with the test being:

@OptIn(ExperimentalCoroutinesApi::class)
class MainViewModelTest : BaseTest() {

Then with the delegation pattern:

class CoroutineTestImpl : CoroutineTest {
    @get:Rule
    override val coroutineScopeRule = CoroutineScopeRule()
}

and test:

class MainViewModelTest : CoroutineTest by CoroutineTestImpl() {

When using the delegation pattern my tests fail and hang. From what I can tell it is due to the two providers that I have appearing to not be initializing properly. If I provide the dispatchers directly in my ViewModel impl then the tests pass with delegation. Wondering if others have run into this problem before and know why these components aren't being initialized. Running coroutines version: 1.6.4

0 Answers0