siger siger - 4 months ago 20
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?


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.