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());
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With