Testing RxJava2 doOnComplete ()

As you can see from the code below, I am trying to check the behavior of a call doOnComplete()occurring in my repository. However, when I make fun of my client’s nested dependency, where I return items with help Observable.just(), it is doOnComplete()no longer called. I believe this is intentional on RxJava2. I am not sure how to get around this.

@Singleton
public class Repository {
    private SomeNetworkClient client;
    private SomeCache cache;

    @Inject
    public Repository(SomeNetworkClient client, SomeCache cache) {
        this.client = client;
        this.cache = cache;
    }

    public Observable<SomeItem> getSomeItem() {
        return client.getSomeItem()
                .doOnComplete(() -> cache.doThisOnComplete())
                .doOnError(throwable -> someError);
    }
}

public class RepositoryTest {
    private Repository testedRepository;
    @Mock
    SomeNetworkClient client;
    @Mock
    SomeCache cache;
    @Mock
    SomeItem someItem;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        testedRepository = new Repository(client, cache);
        when(client.getSomeItem())
            .thenReturn(Observable.just(someItem));
    }

    @Test
    public void thisTestFails() {
        testedRepository.getSomeItem().blockingFirst();
        // This fails because it appears that mocking with
        // Observable.just() makes doOnComplete() not be invoked.
        verify(cache.doThisOnComplete());
    }
}
+4
source share
1 answer

The problem in your code is that it blockingFirst()does not want to listen to the full event. It will immediately return the first element from the stream and remove it from the observable .

:


    testedRepository
            .getSomeItem()
            .test()
            .assertComplete()

+1

Source: https://habr.com/ru/post/1678837/


All Articles