Coroutines body does not cover in unit test code coverage - Android Studio

Viewed 637

When I run the unit test with code coverage, in the code coverage report lambda is shown as not covered.

Code Coverage

Below is my code:

open class CoroutineContextProvider {
    open val main: CoroutineContext by lazy { Dispatchers.Main }
    open val io: CoroutineContext by lazy { Dispatchers.IO }
}
class Hello (
    private val contextProvider: CoroutineContextProvider
) {
    private val mScope = CoroutineScope(contextProvider.main)

    var value: Int = 0

    fun test() {
        mScope.launch(contextProvider.io) {
            println("THIS LINE IS NOT COVERED IN CODE COVERAGE.")
            value++
        }
    }
}

class TestCoroutineContextProvider: CoroutineContextProvider() {
    override val main: CoroutineContext
        get() = Dispatchers.Unconfined
    override val io: CoroutineContext
        get() = Dispatchers.Unconfined
}
class CoroutineTestRule: TestRule {
    private val testCoroutineDispatcher = TestCoroutineDispatcher()
    private val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)

    override fun apply(base: Statement, description: Description?) = object: Statement() {
        override fun evaluate() {
            Dispatchers.setMain(testCoroutineDispatcher)
            base.evaluate()
            Dispatchers.resetMain()
            testCoroutineDispatcher.cleanupTestCoroutines()
        }
    }

    fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) {
        testCoroutineScope.runBlockingTest { block() }
    }
}
class HelloTests {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    val coroutineTestRule = CoroutineTestRule()

    @Test
    fun verify_test() = coroutineTestRule.runBlockingTest {
        val hello = Hello(TestCoroutineContextProvider())
        hello.test()
        assertTrue(hello.value == 1)
    }
}
1 Answers

I would suggest to give it a try to the new code coverage tool developed by JetBrains called Kover. In my brief experience with this tool, it works very well and is fully integrated with Kotlin and Gradle toolchain. The installation of the tool is quite easy, just follow their guides.

I guess it depends on the JaCoCo plugin version you are using, but using the code input you got up there, these are my results related to that coroutine test:

JaCoCo (tool 0.8.7 plugin 0.16.0)

enter image description here

Kover (plugin 0.4.4)

enter image description here enter image description here

Related