如下所示的代码,我试图测试存储库中发生的doOnComplete()
调用的行为。但是,当我模拟注入的依赖项时,我使用Observable.just()
返回项目,doOnComplete()
不再被调用。我相信这是RxJava2故意为之。我不确定如何解决这个问题。
@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());
}
}