【发布时间】:2017-03-10 22:32:53
【问题描述】:
在我的架构中,我使用了一个名为 UseCase 的类来组成一个 observable 并订阅它。 UseCase 在构造函数中接收一个或多个 Repositories,并有一个“execute”方法负责创建 observable 并订阅它。
这是一个简单的例子;
public class MyUseCase {
IRepoA mRepoA;
IRepoB mRepoB;
Scheduler mScheduleOn;
Scheduler mObserveOn;
CompositeSubscription mCompositeSubscription;
public MyUseCase(IRepoA repoA, IRepoB repoB, Scheduler subscribeOn, Scheduler observeOn, CompositeSubscription compositeSubscription) {
mRepoA = repoA;
mRepoB = repoB;
mSubscribeOn = subscribeOn;
mObserveOn = observeOn;
mCompositeSubscription = compositeSubscription;
}
public Observable execute(Observable observable, Subscriber subscriber) {
if (observable == null) {
observable = mRepoA
.fetchLoginPreference()
.map(new Func1<LoginPreference, String>() {
@Override
public String call(LoginPreference loginPreference) {
return loginPreference.getActivationCode();
}
})
.flatMap(new Func1<String, Observable<List<RegistrationField>>>() {
@Override
public Observable<List<RegistrationField>> call(String s) {
return mRepoB.fetchRegistrationFields(s);
}
})
}
mCompositeSubscription.add(observable.subscribeOn(mSubscribeOn).observeOn(mObserveOn).subscribe(observable));
return observable;
}
}
在我看来,这里有几件事要测试,我想知道最好的方法是什么。
1) 我想测试 observables 的组合是否正确。也就是说,我想确保调用了 .map()、.flatMap() 和 .cache()。我之前这样做的方法是使用模拟并验证这些方法是否在模拟上被调用。例如,repoA.fetchLoginPreference() 将返回一个模拟 observable,然后我可以验证该模拟是否调用了 .map() 等等。
2) 我想测试当我订阅 observable 时它的行为是否正确。为了测试这一点,我所做的是使用真正的 Observables 而不是模拟。所以当 repoA.fetchLoginPreference() 被调用时,我会让它返回 Observable.just(mockLoginPreference)。然后我使用 TestSubscriber 订阅生成的 observable 并验证从 Func1 回调中正确调用了模拟。
这看起来是一种理智的做事方式吗?我最终能够测试组合是否正确,并验证当订阅 observable 时它实际上做了它应该做的,但我很好奇是否有更好的方法。
【问题讨论】:
标签: unit-testing rx-java