在 MVP 模式中描绘您的演示者订阅返回观察者的服务的情况:
Picture the situation in an MVP pattern where your presenter subscribes to a service returning an observer:
public void gatherData(){
service.doSomeMagic()
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new TheSubscriber());
}
现在类 TheSubscriber
从视图中调用 onNext
一个方法,比如:
Now the class TheSubscriber
calls onNext
a method from the view, say:
@Override public void onNext(ReturnValue value) {
view.displayWhatever(value);
}
现在,在我的单元测试中,我想验证在非错误情况下调用方法 gatherData()
时,视图的方法 displayWhatever(value)
被调用.
Now, in my unit test I would like to verify that when the method gatherData()
is called on a non-erroneous situation, the view's method displayWhatever(value)
is called.
问题:
有没有干净的方法来做到这一点?
Is there a clean way to do this?
背景:
TheSubscriber
TheSubscriber
我尝试了什么:
感谢您的帮助
假设您正在以类似的方式使用 service
和 view
的接口:
Assuming that you are using interfaces for service
and view
in a similar manner:
class Presenter{
Service service;
View view;
Presenter(Service service){
this.service = service;
}
void bindView(View view){
this.view = view;
}
void gatherData(){
service.doSomeMagic()
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(view::displayValue);
}
}
然后可以提供模拟来控制和验证行为:
It is possible then to provide mock to control and verify behaviour:
@Test void assert_that_displayValue_is_called(){
Service service = mock(Service.class);
View view = mock(View.class);
when(service.doSomeMagic()).thenReturn(Observable.just("myvalue"));
Presenter presenter = new Presenter(service);
presenter.bindView(view);
presenter.gatherData();
verify(view).displayValue("myvalue");
}
这篇关于验证 rxjava 订阅者中的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!