Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing RxJava2 doOnComplete()

As you can see from the code below, I am attempting to test the behavior of the doOnComplete() call occurring within my repository. However, when I mock the injected dependency of my client where I return items using Observable.just(), the doOnComplete() is no longer invoked. I believe this is intentional as per RxJava2. I'm unsure as to how to work 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());
    }
}
like image 621
Timothy Duch Avatar asked Nov 08 '22 21:11

Timothy Duch


1 Answers

The problem in you code is, that blockingFirst() won't care to listen for complete event to happen. It will immediately return the first item from the stream and dispose from observable.

Instead, you may perform assertion this way:


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

like image 122
azizbekian Avatar answered Nov 15 '22 08:11

azizbekian