siger siger - 1 year ago 63
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 = client.request().subscribe(/* log event */);

How can I test this unsubscribing behavior without exposing

I'm thinking of simulating this flow:

  • doSomething()
    called once. Mock
    returns observable O1 that does not emit anything yet. Verify that
    /* log event */
    didn't happen.

  • doSomething()
    called again. Mock
    returns observable O2 that emits immediately. Verify that
    /* log event */

  • 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
like there is a
, which would help verify the number of subscriptions at any time?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download