【问题标题】:how to resolve Suspension functions can be called only within coroutine body如何解决暂停函数只能在协程体内调用
【发布时间】:2021-09-02 00:04:16
【问题描述】:

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

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

只能在协程体内调用挂起函数

这是我的代码

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

我在这里做错了什么?

【问题讨论】:

    标签: android unit-testing kotlin mockito mockk


    【解决方案1】:

    verify 将标准函数作为参数。你需要使用coVerify,它接受一个挂起函数作为它的参数。

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2021-06-05
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2020-11-07
      相关资源
      最近更新 更多