RxJava android mvp 单元测试 NullPointerException [英] RxJava android mvp unit test NullPointerException
问题描述
我是 mvp 单元测试的新手,我想对负责登录的演示者做一个非常基本的测试,我只想断言
I am new to Unit Testing in mvp, I want to make a verrry basic test to the presenter, which is responsible for making login, I just want to assert on
view.onLoginSuccess();
这是演示者代码:
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 这里是测试代码:
Android here is the test code:
@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,我尝试了但没有帮助,我想我做错了什么,谢谢提前.
It just gives me NullPointerException, I think that Knowing how to test the success will help me test everything else, I have read about the TestScheduler, I tried it but did not help, I think I am doing something wrong, thanks in advance.
推荐答案
问题在于您的 TestScheduler
.您应该创建一个辅助类来为您的 observable
提供 schedulers
.喜欢的东西:
The problem is your TestScheduler
. You should create a helper class to provide schedulers
for your observable
. Something likes:
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
而不是到处调用 new
.
P/s: 1 more tip, you should mock your LoginResponse
instead of calling new
everywhere.
这篇关于RxJava android mvp 单元测试 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!