协程主体未包含在单元测试代码覆盖范围内 - Android Studio

Moh*_*dva 9 android unit-testing intellij-idea android-studio kotlin-coroutines

当我使用代码覆盖率运行单元测试时,在代码覆盖率报告中 lambda 显示为未覆盖。

代码覆盖率

下面是我的代码:

open class CoroutineContextProvider {
    open val main: CoroutineContext by lazy { Dispatchers.Main }
    open val io: CoroutineContext by lazy { Dispatchers.IO }
}
Run Code Online (Sandbox Code Playgroud)
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++
        }
    }
}

Run Code Online (Sandbox Code Playgroud)
class TestCoroutineContextProvider: CoroutineContextProvider() {
    override val main: CoroutineContext
        get() = Dispatchers.Unconfined
    override val io: CoroutineContext
        get() = Dispatchers.Unconfined
}
Run Code Online (Sandbox Code Playgroud)
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() }
    }
}
Run Code Online (Sandbox Code Playgroud)
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)
    }
}
Run Code Online (Sandbox Code Playgroud)

GoR*_*RoS 0

我建议尝试一下 JetBrains 开发的新代码覆盖工具Kover。根据我对这个工具的简短体验,它运行得非常好,并且与 Kotlin 和 Gradle 工具链完全集成。该工具的安装非常简单,只需按照他们的指南进行操作即可。

我想这取决于您正在使用的 JaCoCo 插件版本,但是使用您在那里输入的代码,这些是我与该协程测试相关的结果:

JaCoCo(工具0.8.7插件0.16.0)

在此输入图像描述

Kover(插件 0.4.4)

在此输入图像描述 在此输入图像描述