后期编辑
我最终拥有了我的api服务方法suspended
,并按照@LordRaydenMK的建议重构了我的代码。
首先使用库ru.gildor.coroutines:kotlin-coroutines-retrofit
的原因纯粹是出于方便和它是在改装发布支持协同程序的版本之前。
原始问题
几天来,我一直试图模仿API调用,但没有成功。我正在使用以下库:
retrofit
-我想我们都很熟悉它ru.gildor.coroutines:kotlin-coroutines-retrofit
-用于两个有用的协同程序扩展io.mockk:mockk
-用于嘲讽
这是一个嘲笑API响应的简单案例
interface ApiService {
@GET
fun getMyData(@Header("x-value") myValue: String): Call<String>
}
class Usecase(api: ApiService) {
suspend fun execute() {
val result = api.getMyData(value: String).awaitResult()
// do smth with that result for now just return it
return (result as Result.Ok).value
}
}
class UseCaseTest {
private val api = mockk<ApiService>()
@Test
fun testApiCall() {
coEvery { api.getMyData(any()) } returns CallTest.buildSuccess("you did it!")
val result = useCase.execute()
assertEquals(result, "you did it!")
}
}
在上面的例子中,测试挂在awaitResult扩展方法上。
到目前为止,我所尝试的都没有成功:
- mockStatic(ru.gildor.coroutines.reforming.CallAwait(,但没有成功
- 模拟
Call<String>
并执行coEvery { mockedCall.awaitResult() } returns ....
我确信我错过了一些简单的东西,一双新的眼睛会在一英里外发现它。
第一件事:
getMyData
不是suspend
函数,所以在嘲笑它时可能不应该使用coEvery
(尽管我不是Mockk用户(。
话虽如此,Reform确实在本机支持suspend
功能,因此您可以执行以下操作:
interface ApiService {
@GET
suspend fun getMyData(@Header("x-value") myValue: String): String
}
这意味着在您的用例中不需要awaitResult
。在这种情况下,当你嘲笑它时,你确实需要coEvery