我想爲我的Presenter類創建測試,但我在Presenter本身內部的CompositeSubscription實例中遇到問題。當我運行測試,我得到這個錯誤:使用RxJava的Presenter單元測試CompositeSubscription
java.lang.NullPointerException
at rx.subscriptions.CompositeSubscription.add(CompositeSubscription.java:60)
at com.example.Presenter.addSubscription(Presenter.java:67)
at com.example.Presenter.getGummyBears(Presenter.java:62)
這大約是我的演示類:
public class Presenter {
CompositeSubscription compositeSubscription = new CompositeSubscription();
//creation methods...
public void addSubscription(Subscription subscription) {
if (compositeSubscription == null || compositeSubscription.isUnsubscribed()) {
compositeSubscription = new CompositeSubscription();
}
compositeSubscription.add(subscription);
}
public void getGummyBears() {
addSubscription(coreModule.getGummyBears());
}
}
的CoreModule是一個接口(不同模塊的一部分),並有是另一個類CoreModuleImpl,其中包含所有改進的API調用及其對訂閱的轉換。 喜歡的東西:
@Override public Subscription getGummyBears() {
Observable<GummyBears> observable = api.getGummyBears();
//a bunch of flatMap, map and other RxJava methods
return observable.subscribe(getDefaultSubscriber(GummyBear.class));
//FYI the getDefaultSubscriber method posts a GummyBear event on EventBus
}
現在我想要做的就是測試getGummyBears()
方法。 我的測試方法是這樣的:
@Mock EventBus eventBus;
@Mock CoreModule coreModule;
@InjectMock CoreModuleImpl coreModuleImpl;
private Presenter presenter;
@Before
public void setUp() {
presenter = new Presenter(coreModule, eventBus);
coreModuleImpl = new CoreModuleImpl(...);
}
@Test
public void testGetGummyBears() {
List<GummyBears> gummyBears = MockBuilder.newGummyBearList(30);
//I don't know how to set correctly the coreModule subscription and I'm trying to debug the whole CoreModuleImpl but there are too much stuff to Mock and I always end to the NullPointerException
presenter.getGummyBears(); //I'm getting the "null subscription" error here
gummyBears.setCode(200);
presenter.onEventMainThread(gummyBears);
verify(gummyBearsView).setGummyBears(gummyBears);
}
我已經看到來自不同項目的許多測試的例子,但沒有人在使用這種方法訂閱。他們只是返回直接在演示者內部消耗的Observable。在那種情況下,我知道如何寫測試。
什麼是測試我的情況的正確方法?
您是否將演示者放在構造函數中使用'CoreModule'? – skywall
對不起,我忘了在'setUp'方法中添加'presenter = new Presenter(coreModule,eventBus)'這個行 – nicopasso
嗨@nicopasso你能找到解決的辦法嗎? –