nic*_*sso 5 java android unit-testing rx-java
我想为我的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)
Run Code Online (Sandbox Code Playgroud)
这大致是我的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());
    }
}
Run Code Online (Sandbox Code Playgroud)
CoreModule是一个接口(不同模块的一部分),还有另一个类CoreModuleImpl,其中包含所有改进API调用及其转换为Subscriptions.就像是:
@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
}
Run Code Online (Sandbox Code Playgroud)
现在我想做的是测试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);
}
Run Code Online (Sandbox Code Playgroud)
我已经看到了来自不同项目的许多测试示例,但没有人使用此订阅方法.他们只返回直接在演示者内部消费的Observable.在那种情况下,我知道如何编写测试.
测试我的情况的正确方法是什么?
看起来coreModule.getGummyBears()返回 null。只需单步调试一下,应该就很清楚了。使用模拟框架时,如果您没有指定方法调用应在模拟对象上返回什么,则可以从模拟对象上的方法调用返回 null。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           527 次  |  
        
|   最近记录:  |