我正在尝试测试以下案例 从本地获取数据,如果它不可用,则从网络查询。
我的测试看起来像这样:
@Test
public void getProfile_repositoryCachesAfterFirstSubscription_whenProfileAvailableInRemoteStorage() {
// Given that the local data source has data available
setProfileAvailable(profileRemoteDataSource, PROFILE);
// And the remote data source does not have any data available
setProfileNotAvailable(profileLocalDataSource);
// When two subscriptions are set
TestSubscriber<Optional<Profile>> testSubscriber1 = new TestSubscriber<>();
profileRepository.getProfile().subscribe(testSubscriber1);
TestSubscriber<Optional<Profile>> testSubscriber2 = new TestSubscriber<>();
profileRepository.getProfile().subscribe(testSubscriber2);
// Then profile were only requested once from remote and local sources
verify(profileRemoteDataSource).getProfile();
verify(profileLocalDataSource).getProfile();
assertFalse(profileRepository.cacheIsDirty);
testSubscriber1.assertValue(PROFILE);
testSubscriber2.assertValue(PROFILE);
}
private void setProfileNotAvailable(ProfileDataSource dataSource) {
when(dataSource.getProfile()).thenReturn(Flowable.just(Optional.absent()));
}
private void setProfileAvailable(ProfileDataSource dataSource, Optional<Profile> profile) {
// don't allow the data sources to complete.
when(dataSource.getProfile()).thenReturn(Flowable.just(profile).concatWith(Flowable.never()));
}
这是我的存储库
public Flowable<Optional<Profile>> getProfile() {
Flowable<Optional<Profile>> localTask = localDataSource
.getProfile()
.doOnNext(singleData -> {
if (singleData.isPresent()) {
Profile profile = singleData.get();
saveSingleDataInToCash(profile);
}
})
.firstElement().toFlowable();
Flowable<Optional<Profile>> remoteTask = remoteDataSource.getProfile()
.doOnNext(singleData -> {
if (singleData.isPresent()) {
Profile profile = singleData.get();
saveProfile(profile);
}
});
// Query the local storage if available. If not, query the network.
return Flowable.concat(localTask, remoteTask)
.firstElement()
.toFlowable();
}
问题出在何时
// Query the local storage if available. If not, query the network.
Flowable.concat(localTask, remoteTask)
.firstElement()
.toFlowable();
被称为我收到错误 org.mockito.exceptions.verification.TooManyActualInvocations: profileRemoteDataSource.getProfile();
但如果我将.firstElement()更改为.elementAt(1),它可以正常工作,
所以我在这里错过了什么? 预期的行为是当缺席的本地回归应该从网络重新开始。