【发布时间】: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