Migrate MainCoroutineRule

Viewed 527

I want create MainCoroutineRule.
But TestCoroutineScope deprecated since 1.6.0.
How can I migrate it?

Below is my MainCoroutineRule

class MainCoroutineRule(
    val dispatcher: TestCoroutineDispatcher =
        TestCoroutineDispatcher()
): TestWatcher(), TestCoroutineScope by TestCoroutineScope(dispatcher) {
    override fun starting(description: Description) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }
    
    override fun finished(description: Description) {
        super.finished(description)
        cleanupTestCoroutines()
        Dispatchers.resetMain()
    }
}

also, I want to use it on JUnit5. What should I do to migrate TestWatcher?

2 Answers

This is what I have so far, but I don't have a solution for cleanupTestCoroutines

class MainCoroutineRule(
    private val dispatcher: TestDispatcher = StandardTestDispatcher()
) : TestWatcher() {
    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

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

Feel free to edit/modify this with a better solution

My solution will not be perfect, but it was my best.
According to migration tips, runTest does not support replacement for cleanupTestCoroutines().
Instead of that, they support better structured concurrency.
So you don't need to worry about cleanupTestCoroutines().

So, follow is my MainCoroutineExtension.

@OptIn(ExperimentalCoroutinesApi::class)
class MainCoroutineExtension(
    private val testDispatcher: TestDispatcher = StandardTestDispatcher(),
    val testScope: TestScope = TestScope(testDispatcher),
) : BeforeEachCallback, AfterEachCallback {
    override fun beforeEach(context: ExtensionContext) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun afterEach(context: ExtensionContext) {
        Dispatchers.resetMain()
    }

}

@OptIn(ExperimentalCoroutinesApi::class)
fun MainCoroutineExtension.runTest(
    block: suspend TestScope.() -> Unit
) = this.testScope.runTest {
    block()
}

I use JUnit 5 and new coroutine.
So I couldn't use runBlockingTest because it will be deprecated soon.
If you have plan to migrate your coroutine, It will be helpful to you

Related