[英]RxJava android mvp unit test NullPointerException
我是mvp中的单元测试的新手,我想对演示者做一个基本的测试,负责进行登录,我只想断言
view.onLoginSuccess();
这是PresenterCode:
public LoginPresenter(LoginViewContract loginView,
LoginModelContract loginModel,
CurrentUserLoginModelContract currentUserLoginModel,
CompositeDisposable subscriptions) {
this.subscriptions = subscriptions;
this.loginView = loginView;
this.loginModel = loginModel;
this.currentUserLoginModel = currentUserLoginModel;
}
@Override
public void loginPres(LoginRequest loginRequest) {
loginModel.loginUser(loginRequest)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<LoginResponse>() {
@Override
public void onSubscribe(Disposable d) {
subscriptions.add(d);
}
@Override
public void onSuccess(LoginResponse loginResponse) {
// do something with the response
loginView.loginSuccessMessage(token, true);
}
@Override
public void onError(Throwable e) {
loginView.loginFailedErrorMessage();
Timber.e(e, "Error while trying to login");
}
});
}
Android这里是测试代码:
@RunWith(MockitoJUnitRunner.class)
public class LoginPresenterTest {
@Mock
LoginViewContract view;
@Mock
LoginModelContract model;
@Mock
CurrentUserLoginModelContract localModel;
LoginPresenter SUT;
@Before
public void setUp() throws Exception {
compositeDisposable = new CompositeDisposable();
SUT = new LoginPresenter(view, model, localModel, compositeDisposable);
}
@Test
public void name() {
LoginResponse singleResponse = new LoginResponse();
TestScheduler testScheduler = new TestScheduler();
when(model.loginUser(any()))
.thenReturn(Single.just(new LoginResponse()));
SUT.loginPres(any());
}
它只是给了我NullPointerException,我认为知道如何测试成功将帮助我测试其他一切,我已经阅读了关于TestScheduler,我试过但没有帮助,我想我做错了什么,提前谢谢。
您在测试类中创建了一个TestScheduler,但您的Presenter并不了解它。 就像您将视图,模型,localModel和compositeDisposable视为演示者的依赖关系一样,您需要添加两个新的依赖项:您的IO调度Schedulers.computation()
非测试代码中的Schedulers.computation()
和测试中的new TestScheduler()
代码)和您的UI调度程序(非测试代码中的AndroidSchedulers.mainThread()
和测试代码中的new TestScheduler()
)。
完成后,您可以在测试代码中设置2个新的TestSchedulers。 将它们声明为testIoScheduler = new TestScheduler()
和testUiScheduler = new TestScheduler()
。 然后,在调用测试中的方法( SUT.loginPres(any());
)之后,您可以使用testIoScheduler.triggerActions()
和testUiScheduler.triggerActions()
调用调度程序。
问题是你的TestScheduler
。 您应该创建一个帮助程序类来为您的observable
提供schedulers
。 有点喜欢:
class RxProvider{
fun provideIOScheduler()
fun provideAndroidMainScheduler()
}
//Then you can call the rxprovider inside your presenter:
loginModel.loginUser(loginRequest)
.subscribeOn(rxProvider.provideIOScheduler())
.observeOn(rxProvider.provideAndroidMainScheduler())
// inside your test cases
when(rxProvider....).thenReturn(testSchedulers)
P / s:还有1 LoginResponse
,你应该模拟你的LoginResponse
而不是到处调用new
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.