首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin协程使用produces和mockito来模拟生产作业

Kotlin协程使用produces和mockito来模拟生产作业
EN

Stack Overflow用户
提问于 2017-12-02 08:47:31
回答 1查看 828关注 0票数 1

我正在Android应用程序中测试Kotlin协程,并尝试执行以下单元测试

代码语言:javascript
复制
@Test fun `When getVenues success calls explore venues net controller and forwards result to listener`() = 
    runBlocking {
      val near = "Barcelona"
      val result = buildMockVenues()
      val producerJob = produce<List<VenueModel>>(coroutineContext) { result.value }
      whenever(venuesRepository.getVenues(eq(near))) doReturn producerJob // produce corooutine called inside interactor.getVenues(..)

      interactor.getVenues(near, success, error) // call to real method

      verify(venuesRepository).getVenues(eq(near))
      verify(success).invoke(argThat {
        value == result.value
      })
}

交互器方法如下所示

代码语言:javascript
复制
fun getVenues(near: String, success: Callback<GetVenuesResult>,
  error: Callback<GetVenuesResult>) =
postExecute {
  repository.getVenues(near).consumeEach { venues ->
    if (venues.isEmpty()) {
      error(GetVenuesResult(venues, Throwable("No venues where found")))
    } else {
      success(GetVenuesResult(venues))
    }
  }
}

postExecute{..}BaseInteractor上的一个方法,它通过使用kotlin android协程库中的launch(UI)协程的自定义执行器来执行UI线程中的函数

代码语言:javascript
复制
fun <T> postExecute(uiFun: suspend () -> T) =
  executor.ui(uiFun)

然后,repository.getVenues(..)函数也是一个使用produce(CommonPool) {}返回ProducerJob的协程

问题是,它认为交互器函数中成功回调似乎不是按照

代码语言:javascript
复制
verify(success).invoke(argThat {
  value == result.value
})

但是,在调试时,我确实看到交互器函数中的执行到达了consumeEach中的if (venues.isEmpty())行,但是从那里退出并继续测试,显然在验证成功回调时失败。

我是一个新的协程,所以任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2017-12-02 23:13:18

我弄明白了这一点。我发现问题出在这个生产协程上,而不是其他也在使用协程并且工作正常的测试上。我注意到,我实际上错过了模拟ProducingJob上的发送,以便让它实际生成一个值,在本例中是模拟列表。我刚刚添加了将制作作业的模拟更改为

代码语言:javascript
复制
val producerJob = produce { send(result.value) }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47603429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档