模拟返回Kotlin Coroutines Deferred类型的方法的返回值

Joh*_*lly 7 android mockito kotlin retrofit kotlinx.coroutines

我正在使用Kotlin Coroutines,特别是使用Retrofit CoroutineCallAdapterFactory.我正在尝试对一个类进行单元测试,然后使用Retrofit接口(GalwayBusService下面).

interface GalwayBusService {

    @GET("/routes/{route_id}.json")
    fun getStops(@Path("route_id") routeId: String) : Deferred<GetStopsResponse>

}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我有

val galwayBusService = mock()

然后尝试类似下面的内容来模拟调用该方法时返回的内容.但问题是getStops返回一个Deferred值.是否有任何特定的方法建议用于模拟这样的API?

`when`(galwayBusService.getBusStops()).thenReturn(busStopsResponse)
Run Code Online (Sandbox Code Playgroud)

qww*_*sad 8

正确的解决方案是使用CompletableDeferred.它比写作更好,async因为它不会同时启动任何内容(否则您的测试时间可能变得不稳定),并让您更好地控制以什么顺序发生的事情.

例如,您可以将其写为whenever(galwayBusService. getBusStops()).thenReturn(CompletableDeferred(busStopsResponse))好像要无条件地返回已完成的延迟或

val deferred = CompletableDeferred<GetStopsResponse>()
whenever(galwayBusService.getBusStops()).thenReturn(deferred)
// Here you can complete deferred whenever you want
Run Code Online (Sandbox Code Playgroud)

如果你想稍后完成它