我正在尝试在我的项目中使用 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/