Suspend方法的分支覆盖率无法达到100%

问题描述 投票:0回答:1

我编写了一段 Kotlin 代码,我想为其编写单元测试。但我发现我写的单元测试代码仍然无法覆盖100%的分支覆盖率。我该怎么办?

科特林代码:

class MyRepository @Inject constructor(
    @DefaultDispatcher private val dispatcher: CoroutineDispatcher,
    @ApplicationScope private val scope: CoroutineScope,
) {
    private val checkService:ICheckService
    init {
        checkService = CheckService()
    }
    fun fetchData(): String {
        return runBlocking(dispatcher) {
            suspendCoroutine<String> { continuation ->
                println(111)
                scope.launch(dispatcher) {
                    println(222)
                    delay(100)
                    println(333)
                    if(checkService.check()){
                        println(444)
                    }
                    continuation.resume("result")
                }
            }
        }
    }
}

interface ICheckService {
    suspend fun check(): Boolean
}

class CheckService:ICheckService{
    override suspend fun check(): Boolean {
        return true
    }

}

UT代码:

class MyRepositoryTest {
    private lateinit var myRepository: MyRepository
    private val dispatcher = StandardTestDispatcher()
    private lateinit var scope: TestScope

    @Before
    fun setUp() {
        scope = TestScope(dispatcher)
        myRepository = MyRepository(dispatcher, scope)
    }

    @Test
    fun testMyRepository() = scope.runTest {

        withContext([Dispatchers.IO](http://dispatchers.io/)){
            myRepository.fetchData()
        }

    }
}

另外,如果我改变

的对象
myRepository to myRepository=mockk (relaxed=true)

,覆盖率将为 0%,并且不会执行任何代码。

android android-studio unit-testing android-jetpack android-testing
1个回答
0
投票

我假设您缺失的承保范围是由于

if(checkService.check())
始终采用
true
分支。

首先,替换:

class MyRepository @Inject constructor(
    @DefaultDispatcher private val dispatcher: CoroutineDispatcher,
    @ApplicationScope private val scope: CoroutineScope,
) {
    private val checkService:ICheckService
    init {
        checkService = CheckService()
    }

与:

class MyRepository @Inject constructor(
    @DefaultDispatcher private val dispatcher: CoroutineDispatcher,
    @ApplicationScope private val scope: CoroutineScope,
    private val checkService: ICheckService = CheckService()
) {

换句话说,使用您选择的依赖倒置框架来注入

ICheckService
实现,只需默认为您的标准实现即可。现在您可以编写提供
ICheckService
测试假的测试来处理其他场景。

然后,编写一个测试用例,使用从

ICheckService
返回
false
check()
实现,以补充
true
返回的
CheckService

© www.soinside.com 2019 - 2024. All rights reserved.