我试图为登录请求测试此observable,但永远不会调用订阅者onNext和onCompleted方法。
return mDeviceRepository.getDeviceId()
.flatMap(new Func1<String, Observable<LoginResponse>>() {
@Override
public Observable<LoginResponse> call(String deviceId) {
return mAuthRepository.login(deviceId, mUsername, mHashedPassword);
}
})
.flatMap(new Func1<LoginResponse, Observable<LoginResponse>>() {
@Override
public Observable<LoginResponse> call(LoginResponse loginResponse) {
mSessionRepository.storeSession(UserSession.fromLoginReponse(loginResponse));
mUserRepository.storeUser(loginResponse.getUser());
return Observable.just(loginResponse);
}
});
我的测试看起来像这样:
loginUseCase.setCredentials("testuser", "testpassword");
when(mockDeviceRepository.getDeviceId()).thenReturn(Observable.just("testdeviceid"));
when(mockAuthRepository.login("testdeviceid", "testuser", "testpassword")).thenReturn(Observable.just(new LoginResponse()));
testSubscriber = new TestSubscriber();
loginUseCase.buildUseCaseObservable().toBlocking().subscribe(testSubscriber);
testSubscriber.assertCompleted();
testSubscriber.assertValueCount(1);
答案 0 :(得分:1)
尝试
loginUseCase.buildUseCaseObservable().subscribe(testSubscriber);
PS:如果你想要副作用,不要在flatMap中进行。使用副作用操作符,例如
return mDeviceRepository.getDeviceId()
.flatMap(new Func1<String, Observable<LoginResponse>>() {
@Override
public Observable<LoginResponse> call(String deviceId) {
return mAuthRepository.login(deviceId, mUsername, mHashedPassword);
}
})
.doOnNext(new Action1<LoginResponse>() {
@Override
public void call(String loginResponse) {
mSessionRepository.storeSession(UserSession.fromLoginReponse(loginResponse));
mUserRepository.storeUser(loginResponse.getUser());
}
})
.flatMap(new Func1<LoginResponse, Observable<LoginResponse>>() {
@Override
public Observable<LoginResponse> call(LoginResponse loginResponse) {
return Observable.just(loginResponse);
}
});
答案 1 :(得分:1)
在TestSubscriber中,assertTerminalEvent()而不是assertCompleted()怎么样? 所有运算符都在同一个线程上运行,因此如果达到了TestSubscriber断言,则会在流中的某处抛出异常