我正在为我的 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/