問題描述
在 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?
背景:
- 我正在使用 mockito 來驗證交互,當然還有更多
- Dagger 正在注入除
TheSubscriber
之外的整個 Presenter
- I'm using mockito to verify the interactions and a lot more of course
- Dagger is injecting the entire presenter except for
TheSubscriber
我嘗試了什么:
- 注入訂閱者并在測試中模擬它.我覺得有點臟,因為如果我想改變演示者與服務交互的方式(說不是 Rx),那么我需要改變很多測試和代碼.
- 模擬整個服務.這還不錯,但需要我模擬很多方法,但我并沒有完全達到我想要的效果.
- 在互聯網上四處查找,但似乎沒有人有一種干凈直接的方法來做到這一點
感謝您的幫助
推薦答案
假設您正在以類似的方式使用 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 訂閱者中的交互的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!