lundi 23 novembre 2015

Controlling emission of Observable items in unit tests

I have a class that subscribes to a dependency-provided observable and stores the resulting subscription, so that it can be cancelled if a new request comes in.

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 */);
    }
}

How can I test this unsubscribing behavior without exposing subscription?

I'm thinking of simulating this flow:

  • doSomething() called once. Mock client returns observable O1 that does not emit anything yet. Verify that /* log event */ didn't happen.
  • doSomething() called again. Mock client returns observable O2 that emits immediately. Verify that /* log event */ happened.
  • Have O1 emit an item, verify /* log event */ didn't happen again.

If that's a recommended approach, I don't know how to have O1 emit items at specific steps of my test.

Otherwise, is there any kind of TestObservable like there is a TestSubscriber, which would help verify the number of subscriptions at any time?

Aucun commentaire:

Enregistrer un commentaire