android - 如何使用 MockK 测试挂起功能?

标签 android unit-testing kotlin mockito mockk

我正在为我的 Datarepository 层编写一个单元测试,它只是调用一个接口(interface)。
我正在使用 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>
}

最佳答案

是的,你应该把 dataRepository.getCharacters()调用runBlocking .
verify应替换为 coVerify .
最后,测试应该如下所示:

@Test
fun getCharacters() {
    val respose = runBlocking { dataRepository.getCharacters() }
    
    coVerify { apiServiceInterface.getDataFromApi() }
}
此外,由于您想验证它只发生过一次,您需要调用 coVerify精确参数 coVerify(exactly = 1)

关于android - 如何使用 MockK 测试挂起功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69014652/

相关文章:

java - 在 Android 上获取 Cognito 凭证

android - RecyclerView 不刷新

java - Mockito:如何 stub 无效方法以在调用时运行一些代码

java - AssertJ JSON 属性检查

android - 两个相同的 String 不会等于 true

android - Firebase电话身份验证限制

android - Quickblox 错误 : "Unexpected Signature" while login ChatService in Android

android - 如何调用Robolectric的ShadowWifiManager.setScanResults()?

java - 如何创建 OkHttp 所需的虚拟 ResponseBody 对象?

android - 如何在 Android Kotlin 中抑制字符串常量的拼写检查?