Skip to content

Testing lifecycle of a CoroutineScope #1504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
thibseisel opened this issue Sep 4, 2019 · 2 comments
Closed

Testing lifecycle of a CoroutineScope #1504

thibseisel opened this issue Sep 4, 2019 · 2 comments

Comments

@thibseisel
Copy link
Contributor

Say I have a class that encapsulates the actorCounter coroutine (defined here in the docs):

class IntCounter(scope: CoroutineScope) {
    private val actor = scope.counterActor()

    suspend fun get(): Int {
        val deferred = CompletableDeferred<Int>()
        counter.send(CounterMessage.Get(deferred))
        return deferred.await()
    }
    
    suspend fun inc() {
        counter.send(CounterMessage.Increment)
    }
}

If I write the following test for this class

fun `Initial counter value should be zero`() = runBlockingTest {
    val counter = IntCounter(this)
    val initialValue = counter.get()
    assertEquals(0, initialValue)
}

Then the test fails with UncompletedCoroutinesError: Test finished with active jobs [ActorCoroutine[Active]@7cbc5d3, which is expected since the actor coroutine is still running after the test block ends.

But then, what is the recommended way of writing such a test ?
I tried multiple constructs, such as

  • nested runBlockingTest
  • wrap in coroutineScope
  • cancelling children with coroutineContext.chancelChildren()

But all are failing the test with various exceptions (respectively UncompletedCoroutinesError, IllegalStateException: This job has not completed yet, and JobCancellationException).

Thanks in advance !

@elizarov
Copy link
Contributor

elizarov commented Sep 4, 2019

Thanks for a use-case. That will be covered in #1365. I'm closing it as a duplicate.

@elizarov elizarov closed this as completed Sep 4, 2019
@lukas1
Copy link

lukas1 commented Nov 5, 2020

I found a workaround that makes the tests pass.

Using JUnit 5 I use following extension:

class CoroutinesExecutorExtension(
    private val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : BeforeEachCallback, AfterEachCallback, ParameterResolver {
    override fun beforeEach(context: ExtensionContext?) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun afterEach(context: ExtensionContext?) {
        testDispatcher.cleanupTestCoroutines()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun supportsParameter(
        parameterContext: ParameterContext?,
        extensionContext: ExtensionContext?
    ): Boolean {
        return parameterContext?.parameter?.type == TestCoroutineDispatcher::class.java
    }

    override fun resolveParameter(
        parameterContext: ParameterContext?,
        extensionContext: ExtensionContext?
    ): Any = testDispatcher

}

Then you can test like this:

@ExtendWith(CoroutinesExecutorExtension::class)
class TestClass(private val testCoroutineDispatcher: TestCoroutineDispatcher) {

    fun `Initial counter value should be zero`() = runBlockingTest {
        val counter = IntCounter(TestCoroutineScope(testCoroutineDispatcher))
        val initialValue = counter.get()
        assertEquals(0, initialValue)
    }

}

Not sure if there is any downside to this, but it worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants