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)
| 归档时间: |
|
| 查看次数: |
291 次 |
| 最近记录: |