siger siger - 1 month ago 6
Android Question

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?

Answer

With a bit more experience in this domain, today I would have the dependency return a Subject, and assert that this subject only has one observer after calling doSomething() twice.

Comments