gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:38:08 27 4
gpt4 key购买 nike

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

Code Coverage

下面是我的代码:

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

最佳答案

我建议尝试使用 JetBrains 开发的名为 Kover 的新代码覆盖率工具。 .在我对这个工具的简短体验中,它运行良好,并且与 Kotlin 和 Gradle 工具链完全集成。该工具的安装非常简单,只需关注 their guides .
我想这取决于您使用的 JaCoCo 插件版本,但是使用您在那里输入的代码,这些是我与该协程测试相关的结果:
JaCoCo(工具 0.8.7 插件 0.16.0)
enter image description here
Kover (插件 0.4.4)
enter image description here
enter image description here

关于android - 协程主体未涵盖在单元测试代码覆盖范围内 - Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62402633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com