【问题标题】:Timeout test does not return TimeoutException - rxjava超时测试不返回 TimeoutException - rxjava
【发布时间】:2018-02-27 11:49:22
【问题描述】:

测试失败,因为没有抛出异常。它只是完成而不是超时。

    @Test
    fun timeout() {
        val testScheduler = TestScheduler()

        val sub = Observable.just(true)
                .filter{ it -> !it }
                .timeout(10, TimeUnit.SECONDS, testScheduler)

        val testSubscriber = sub.subscribeOn(testScheduler).test()

        testScheduler.advanceTimeBy(20, TimeUnit.SECONDS)
        testSubscriber.assertError(TimeoutException::class.java)
    }

我已经在这个街区待了一个多小时,我只是不明白它为什么会失败。这可能是非常明显的事情,但我觉得我需要另一双眼睛来为我指出。

【问题讨论】:

  • just 是一个有限源,序列在没有任何项目且没有延迟的情况下完成。你想完成什么?
  • 啊当然...
  • 我想你可以把它改成Observable.fromCallable(() -> { return true; }),它会按预期运行。 just 是一个阻塞调用。
  • @Tuby 完全错误。
  • @Tuby fromCallable 仍然是有限的,然而,OP 试图复制一个热的、非终止的 Observablejust 也不是阻塞的,而是同步的。

标签: kotlin rx-java rx-java2


【解决方案1】:

这是一个得到预期结果的测试:

@Test
fun timeout() {
    val testScheduler = TestScheduler()

    val sub = Observable.just(true) // 1
            .delaySubscription(Observable.never<Boolean>()) // 2
            .timeout(10, TimeUnit.SECONDS, testScheduler) // 3
    val testSubscriber = sub.subscribeOn(testScheduler).test()

    testScheduler.advanceTimeBy(20, TimeUnit.SECONDS)
    testSubscriber.assertError(TimeoutException::class.java)

下面是对发生的事情的解释:

  1. 我们只需要一个Observable 来开始,你之前的过滤器只是让它变成一个空的
  2. 我们想要 delay the subscription 处理无法完成的事情,所以一个替代方案是 Observable 而不是 never 发出
  3. 从这里开始,和你一样

【讨论】:

  • +1 表示“所以一个替代方案是 Observable 而不是从不发射”。在我的测试中,原始的 observable 仍在发出有效的 onNext(),因此如果您提前时间,成功的发射会在 timeout() 有机会发送异常之前发送。
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 2020-12-09
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多