1

I have a completable that looks like below which I'm trying to test with Mockito.

completable
        .doOnSubscribe {
            list.add(item)
        }.doOnError {
            list.remove(item)
            //do other stuff
        }.doOnComplete {
            list.remove(item)
            //do other stuff
        }

That list manages a state that might be accessed elsewhere (another fragment or activity) to indicate how many items are still processing or if they're all complete.

I can't figure out how to unit test this directly other than creating a add() and remove() method, and then calling those, and using a spy to confirm it was called since subscribing to this immediately adds and removes it.

That seems a little overkill so I'm wondering if I'm missing a way to just trigger the doOnSubscribe portion?

Ben987654
  • 3,280
  • 4
  • 27
  • 50
  • It isn't clear what, in fact, you are trying to test. Testing whether RxJava works is a waste of time, so you may be trying to test whether your observer chain works. Mocking up `list` to respond to calls may be the only way to check the observer chain. – Bob Dalgleish Oct 31 '18 at 15:16
  • Ya, I'm trying to test that list.add actually gets called, since if I only test the outcome of the chain, it'll always be 0. – Ben987654 Oct 31 '18 at 16:19

1 Answers1

3

As Bob suggested, mock up a java.util.List and verify it:

import static org.mockito.Mockito.*;

import java.util.List;

import org.junit.Test;

import io.reactivex.subjects.CompletableSubject;

public class TestMockitoCalls {

    @Test
    public void test() {
        @SuppressWarnings("unchecked")
        List<Integer> list = mock(List.class);

        CompletableSubject source = CompletableSubject.create();

        source.doOnSubscribe(v -> list.add(1))
        .doOnError(e -> list.remove(1))
        .doOnComplete(() -> list.remove(1))
        .subscribe();

        source.onComplete();

        verify(list).add(1);
        verify(list).remove(1);
        verifyNoMoreInteractions(list);
    }
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192