android - 如何解决暂停函数只能在协程体内调用

标签 android unit-testing kotlin mockito mockk

我正在尝试在我的项目中使用 MockK,

当我尝试验证接口(interface)中的 api 调用时出现错误

Suspension functions can be called only within coroutine body

这是我的代码

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 kotlinx.coroutines.test.runBlockingTest
import org.junit.Test

class DataRepositoryTest {
    @MockK
    private lateinit var apiServiceInterface: ApiServiceInterface

    @InjectMockKs
    private lateinit var dataRepository: DataRepository

    @Test
    fun getCharacters() {
        runBlockingTest {
            val respose = dataRepository.getCharacters()
            verify { apiServiceInterface.getDataFromApi() } // HERE IS THE ERROR
        }
    }
}

数据存储库

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>
}

我在这里做错了什么?

最佳答案

verify 将标准函数作为参数。您需要使用 coVerify,它以挂起函数作为参数。

关于android - 如何解决暂停函数只能在协程体内调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69021725/

相关文章:

java - 为 Android 设置 Libgdx Bullet 包装器时出现问题

android - 缺少 dagger2 编译错误

unit-testing - 为从中读取的函数填充 os.Stdin

unit-testing - 如何为一个测试方法运行多个测试用例

android - 在 Android Jetpack Compose 中使用 State 时出现 java.lang.IllegalStateException

android - 如何根据条件选择启动Activity

android - GeoLocation API 在移动设备上的安全性如何?

unit-testing - Sauce Labs 替代品

kotlin - 为什么要始终使用不可变集合接口(interface)来声明在 Kotlin 中未发生变异的集合?

android - Observable.concat(observable,observable) 的奇怪结果