验证rxjava用户互动 [英] Verify interactions in rxjava subscribers
问题描述
照片中的MVP模式的情况下你的presenter订阅返回一个观察者服务:
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(值)
被调用。
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?
背景
- 我使用到的Mockito验证的互动和更大量的课程
- 匕首被注入整个presenter除了
TheSubscriber
- I'm using mockito to verify the interactions and a lot more of course
- Dagger is injecting the entire presenter except for
TheSubscriber
有什么我试过
- 注入的用户,并在测试中嘲笑它。看起来有点脏了我,因为如果我想改变presenter与服务交互(说不RX)的方式,然后我需要改变大量的测试和code。
- 莫克整个服务。这不是那么糟糕,但要求我嘲笑了很多方法,我并没有完全达到我想要的东西。
- 抬头一看周围的互联网,但似乎没有人有这样 干净笔直的路
- Inject the subscriber and mock it in the tests. Looks a bit dirty to me, because if I want to change the way the presenter interacts with the service (Say not Rx) then I need to change a lot of tests and code.
- Mock the entire service. This was not so bad, but requires me to mock a lot of methods and I didn't quite reach what I wanted.
- Looked up around the internet, but no one seems to have a clean straight way of doing this
感谢您的帮助。
推荐答案
假设你正在使用接口服务
和视图
以类似的方式:
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用户互动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!