在单元测试中控制 Observable 项的发射

Controlling emission of Observable items in unit tests

我有一个 class 订阅依赖提供的可观察对象并存储结果订阅,以便在有新请求时可以取消订阅。

public class A {
    private final Client client;

    private Subscription subscription;

    public void doSomething() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }

        subscription = client.request().subscribe(/* log event */);
    }
}

如何在不暴露 subscription 的情况下测试这种退订行为?

我正在考虑模拟这个流程:

如果这是推荐的方法,我不知道如何让 O1 在测试的特定步骤发射物品。

不然,有没有像TestSubscriber一样的TestObservable,可以随时验证订阅人数?

有一个TestScheduler来计时:

The TestScheduler is useful for debugging. It allows you to test schedules of events by manually advancing the clock at whatever pace you choose.

您可以使用 observable.doOnSubscribe(action)doOnUnsubscribe(action) 来监控订阅事件。

凭借在该领域的更多经验,今天我将拥有依赖关系 return a Subject,并断言该主题在调用 doSomething() 两次后只有一个观察者。