我正在尝试执行单元测试和模拟改型调用,但没有成功。当我运行测试时,我只打印了end。我还应该打印onResponse()。
当我运行我的应用程序时,代码工作正常,只是测试没有调用模拟的API调用。
视图模型中的方法:
fun loadSensors() {
CoroutineScope(Dispatchers.IO).launch {
sensorsService.getUserSensors(getUserToken(), getUserId())
.enqueue(object : Callback<List<Long>> {
override fun onResponse(
call: Call<List<Long>>,
response: Response<List<Long>>
) {
println("onResponse()")
}
override fun onFailure(call: Call<List<Long>>, t: Throwable) {
println("onFailure()")
}
})
}
println("end")
}
接口:
@GET("/sensors")
fun getUserSensors(): Call<List<Long>>
应用模块:
@Provides
@Singleton
fun provideRetrofitFactory(gsonConverterFactory: GsonConverterFactory): Retrofit {
val client = OkHttpClient.Builder().build()
return Retrofit.Builder()
.baseUrl("http://<url>")
.addConverterFactory(gsonConverterFactory)
.client(client)
.build()
}
测试:
@OptIn(DelicateCoroutinesApi::class)
private val mainThreadSurrogate = newSingleThreadContext("UI thread")
@OptIn(ExperimentalCoroutinesApi::class)
@BeforeAll
fun beforeAll() {
Dispatchers.setMain(mainThreadSurrogate)
}
@Test
fun loadSensors() {
val mockedCall = mockk<retrofit2.Call<List<Long>>>()
every { mockedCall.enqueue(any()) } answers {
val callback = args[0] as retrofit2.Callback<List<Long>>
val response = retrofit2.Response.success(200, listOf(1L, 2L, 3L))
callback.onResponse(mockedCall, response)
}
every { sensorsService.getUserSensors(any(), any()) } answers {
mockedCall
}
}
1条答案
按热度按时间gdx19jrr1#
我建议你看看
MockWebServer
,我相信用它你可以做任何你想做的事情。