如何解决挂起函数只能在协程体内调用的问题

BRD*_*oid 4 android unit-testing mockito kotlin mockk

我正在尝试在我的项目中使用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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

数据存储库

class DataRepository @Inject constructor(
    private val apiServiceInterface: ApiServiceInterface
) {
    suspend fun getCharacters(): Result<ArrayList<Character>> = kotlin.runCatching{
        apiServiceInterface.getDataFromApi()
    }
}
Run Code Online (Sandbox Code Playgroud)

界面

interface ApiServiceInterface {
    @GET("api/characters")
    suspend fun getDataFromApi(): ArrayList<Character>
}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

Ten*_*r04 15

verify采用标准函数作为参数。您需要使用coVerifywhich 采用挂起函数作为 it\xe2\x80\x99s 参数。

\n