Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 如何测试CompletableEmitter.tryOnError()_Kotlin_Rx Java2 - Fatal编程技术网

Kotlin 如何测试CompletableEmitter.tryOnError()

Kotlin 如何测试CompletableEmitter.tryOnError(),kotlin,rx-java2,Kotlin,Rx Java2,我有下一个代码: inline fun completable(crossinline action: () -> Unit) = completable(action, {}) inline fun completable( crossinline action: () -> Unit, crossinline finally: () -> Unit ): Completable { return Completable.create

我有下一个代码:

inline fun completable(crossinline action: () -> Unit) = completable(action, {})

inline fun completable(
        crossinline action: () -> Unit,
        crossinline finally: () -> Unit
): Completable {
    return Completable.create { emitter ->
        try {
            action()
            emitter.onComplete()
        } catch (t: Throwable) {
            // Attempts to emit the specified {@code Throwable} error if the downstream
            // hasn't cancelled the sequence or is otherwise terminated, returning false
            // if the emission is not allowed to happen due to lifecycle restrictions.
            // <p>
            // Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called
            // if the error could not be delivered.
            emitter.tryOnError(t)
        } finally {
            finally()
        }
    }
}
如果将异常传递给处理程序,则会引发异常

不幸的是,这项测试并不稳定。我认为在这种情况下,多线程处理非常棘手


我可以改进这个测试吗?也许可以使用
TestScheduler
来准确模拟第一个异常终止流后第二个异常到达的情况?

您不需要并发性,但在抛出异常之前要处理消费者:

List errors=new ArrayList();
setErrorHandler(errors::add);
试一试{
TestObserver to=新的TestObserver();
可完成(()->{
to.dispose();
抛出新的RuntimeException();
})
.认购;
}最后{
RxJavaPlugins.setErrorHandler(null);
}
assertTrue(errors.isEmpty());

它可以工作!我在kotlin缓存方面遇到了一些问题,但我确实进行了干净的检查,检查结果是否符合预期。
@Test
fun `Completable do not crash when terminated`() {
    var ex: Throwable? = null
    RxJavaPlugins.setErrorHandler { t -> ex = t }

    Completable.mergeArray(
            completable {
                throw IOException("test1")
            }.subscribeOn(Schedulers.io()),
            completable {
                throw IOException("test2")
            }.subscribeOn(Schedulers.io())
    ).onErrorComplete()
            .blockingAwait()

    RxJavaPlugins.setErrorHandler(null)

    ex?.let {
        throw it
    }
}