2

有没有办法让我模拟一个挂起函数,这样它就不会发出数据或者它会发出错误。使用 RxJava 2,我可以模拟该函数以返回 Observable.error 或 Observable.never,但我在 kotlin 协程中找不到等效功能。这是需要模拟的功能。

override suspend fun execute(param: Params): List<NewsModel> {
    return dataManager.getNewsCoro(param.newsType)
}

从我的 viewModel 我以这种方式调用挂起函数

 fun getNews(newsType: NewsType) {

    liveData.postValue(NewsViewState(AsyncViewResource.loading()))

    launch {
      tryCatchFinally({
        val newsList = getNews.execute(GetNewsCoro.Params(newsType))
        liveData.postValue(NewsViewState(AsyncViewResource.success(newsList)))
      }, {

        liveData.postValue(NewsViewState(AsyncViewResource.error(it)))
      }, {}, false)
    }

  }

在该视图模型的测试类中,我想模拟执行函数,使其永远不会返回数据,这样我就可以测试传递给 liveData 的数据是否是我所期望的。在 RxJava 中,我可以模拟返回 Observable.never() 和 Observable.error() 的函数。但是对于协程,我迷失了寻找模拟它的方法。

4

1 回答 1

0

您可以使用pauseDispatcher()暂停您的TestCoroutineDispatcher.

根据文档

暂停时,调度器不会自动执行任何协程,必须调用 runCurrent 或 AdvanceTimeBy 或 AdvanceUntilIdle 来执行协程。

@Test
fun test() {
  val testCoroutineDispatcher = TestCoroutineDispatcher()
  val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)
  testCoroutineScope.run {
    testCoroutineDispatcher.pauseDispatcher()

    viewModel.getNews(newsType)

     // Check if liveData is loading state or not.
  }
}
于 2021-06-29T10:46:56.883 回答