首页 > 解决方案 > 如何使用 MockK 测试挂起功能?

问题描述

我正在为我的 Datarepository 层编写一个单元测试,它只是调用一个接口。我正在使用 Kotlin、协程和 MockK 进行单元测试。在 MockK 中,我如何验证我已经调用apiServiceInterface.getDataFromApi()过并且只发生过一次?我应该把代码放在 runBlocking 中吗?

这是我的代码:

单元测试

import com.example.breakingbad.api.ApiServiceInterface
import com.example.breakingbad.data.DataRepository
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import org.junit.Test

存储库

class DataRepositoryTest {
    @MockK
    private lateinit var apiServiceInterface: ApiServiceInterface

    @InjectMockKs
    private lateinit var dataRepository: DataRepository

    @Test
    fun getCharacters() {
            val respose = dataRepository.getCharacters()
            verify { apiServiceInterface.getDataFromApi() }
    }
}

    class DataRepository @Inject constructor(
    private val apiServiceInterface: ApiServiceInterface
) {
    suspend fun getCharacters(): Result<ArrayList<Character>> = kotlin.runCatching{
        apiServiceInterface.getDataFromApi()
    }
}

界面

interface ApiServiceInterface {
    @GET("api/characters")
    suspend fun getDataFromApi(): ArrayList<Character>
}

标签: androidunit-testingkotlinmockitomockk

解决方案


是的,您应该将dataRepository.getCharacters()调用放在runBlocking.

并且verify应该替换为coVerify.

最后,测试应该如下所示:

@Test
fun getCharacters() {
    val respose = runBlocking { dataRepository.getCharacters() }
    
    coVerify { apiServiceInterface.getDataFromApi() }
}

此外,由于您想验证它只发生过一次,您需要coVerify使用完全参数调用coVerify(exactly = 1)


推荐阅读