测试 RxJava2 doOnComplete()
Testing RxJava2 doOnComplete()
正如您从下面的代码中看到的,我正在尝试测试我的存储库中发生的 doOnComplete()
调用的行为。但是,当我使用 Observable.just()
模拟我的客户端的注入依赖项时,我 return 项目不再调用 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());
}
}
你代码中的问题是,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。
相反,您可以这样执行断言:
testedRepository
.getSomeItem()
.test()
.assertComplete()
正如您从下面的代码中看到的,我正在尝试测试我的存储库中发生的 doOnComplete()
调用的行为。但是,当我使用 Observable.just()
模拟我的客户端的注入依赖项时,我 return 项目不再调用 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());
}
}
你代码中的问题是,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。
相反,您可以这样执行断言:
testedRepository
.getSomeItem()
.test()
.assertComplete()