android - 如何使用 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>
}
解决方案
是的,您应该将dataRepository.getCharacters()
调用放在runBlocking
.
并且verify
应该替换为coVerify
.
最后,测试应该如下所示:
@Test
fun getCharacters() {
val respose = runBlocking { dataRepository.getCharacters() }
coVerify { apiServiceInterface.getDataFromApi() }
}
此外,由于您想验证它只发生过一次,您需要coVerify
使用完全参数调用coVerify(exactly = 1)
推荐阅读
- node.js - React 如何添加自定义 js 文件 web 应用程序
- c# - 在 C# 中使用类型作为函数参数创建通用对象
- sql - MSSQL - 如何为分组选择查询获取聚合值的加法
- entity-framework - LINQ:一次查询两个表
- angular - Angular - 应用程序在手动页面刷新时未正确路由
- java - 线程“DisconnectableInputStream 源阅读器”中的异常 org.gradle.api.UncheckedIOException:java.io.IOException:句柄无效
- objective-c - Ionic 4:如何导入自定义插件
- python - 树莓派中的 c = max(cnts, key=cv2.contourArea) 错误
- android - 在 RecyclerView.ViewHolder 中显示列表的最佳实践?
- c# - 为什么我的 DLL 在执行后仍被 Revit 使用?