When I run the unit test with code coverage, in the code coverage report lambda is shown as not covered.
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)
}
}



