我想为我的 Presenter 类创建一个测试,但我遇到了 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)
这大致是我的 Presenter 类:
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 是一个接口(interface)(不同模块的一部分),还有另一个类 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.getGummyBears()
正在返回 null。只需逐步调试,它应该非常清楚。使用模拟框架时,如果您没有指定方法调用应在模拟对象上返回什么,则可以从模拟对象上的方法调用返回 null。
关于java - 使用 RxJava CompositeSubscription 进行 Presenter 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39726659/