【问题标题】:Coroutines body does not cover in unit test code coverage - Android Studio协程主体未涵盖在单元测试代码覆盖范围内 - Android Studio
【发布时间】:2020-10-05 17:10:36
【问题描述】:

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

下面是我的代码:

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)
    }
}

【问题讨论】:

  • 你找到什么了吗?我现在面临同样的问题。
  • 在某种程度上我在课堂上的所有挂起函数都没有显示任何覆盖范围。
  • 能解决这个问题吗?

标签: android unit-testing android-studio intellij-idea kotlin-coroutines


【解决方案1】:

我建议尝试使用 JetBrains 开发的名为 Kover 的新代码覆盖率工具。在我对这个工具的简短体验中,它运行良好,并且与 Kotlin 和 Gradle 工具链完全集成。安装工具很简单,关注their guides即可。

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

JaCoCo(工具 0.8.7 插件 0.16.0)

Kover(插件 0.4.4)

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多