首页 > 解决方案 > rxjava testScheduler 竞争条件

问题描述

我偶然发现了一个奇怪的 testScheduler 行为,我无法理解。下面的代码被大大简化了,但它源于现实生活中的问题。

考虑这个测试:

@Test
fun testSchedulerFun(){

    val testScheduler = TestScheduler()

    val stringsProcessor = PublishProcessor.create<String>()

    val completable = Completable.complete()

    completable
        .doOnComplete { stringsProcessor.onNext("onComplete") }
        .subscribeOn(testScheduler)
        .subscribe()

    val testSubscriber = stringsProcessor
        .subscribeOn(testScheduler) //this line of code messes the test
        .test()

    testScheduler.triggerActions()

    testSubscriber
        .assertValues("onComplete")

}

**当我订阅 test stringsProcessorontestScheduler时,测试失败。当我删除该行时,它成功了。**

我看到的事件流程是:

  1. 触发动作
  2. 正在订阅 completable 和 stringsProcessor 并将它们的事件传播到下游。
  3. 显然,在 testSubscriber 完成stringsProcessor.onNext("onComplete")评估。

我想知道为什么

标签: unit-testingkotlinrx-javarx-java3

解决方案


测试失败的原因是因为stringProcessor在您调用它时没有订阅者onNext。该订阅者仅在您添加了“这条线搞砸了”之后才出现subscribeOn

不涉及竞争条件,因为一切都以确定的顺序在同一个线程上运行:

  1. 当代码执行completable ... subscribe()部分时testScheduler,将执行 doOnComplete 调用的任务排队。
  2. 当代码执行该test部分时,另一个任务会排队testScheduler,它将观察处理器。
  3. triggerActions 执行任务 1,它不向任何订阅者发出值,然后执行任务 2,现在准备观察处理器,但什么也没有。

推荐阅读