代码之家  ›  专栏  ›  技术社区  ›  John O'Reilly

模拟返回Kotlin协程延迟类型的方法的返回值

  •  5
  • John O'Reilly  · 技术社区  · 8 年前

    我正在使用Kotlin协同程序,特别是使用改装的 CoroutineCallAdapterFactory GalwayBusService 下面)。

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

    在我的单元测试中

    val galwayBusService = mock()

    然后尝试下面的方法来模拟调用该方法时返回的内容。问题是 getStops Deferred 价值观。对于这样的模拟api,有什么特别的方法值得推荐吗?

    `when`(galwayBusService.getBusStops()).thenReturn(busStopsResponse)
    
    2 回复  |  直到 8 年前
        1
  •  12
  •   qwwdfsad    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
    

    如果你想以后再完成的话

        2
  •  4
  •   John O'Reilly    8 年前

    所以,解决这个问题的方法是 async

    whenever(galwayBusService. getBusStops()).thenReturn(async { busStopsResponse })
    

    贷方btw to https://twitter.com/_rafaeltoledo 为了答案!