我正在尝试使用Robolectric(3.1-rc1)测试一些方法
/ *方法代码* /
public void sendSomething(String prop1, String prop2){
Observable<SomeResponse> service = mSomeWebServiceAPI.login(new SomeRequest(prop1, prop2));
Subscription subscription = service.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread()).subscribe(response -> {
if(isSuccess()){
// ... some code && inserting data to sqlite
if (isViewPresent()) getView().onSuccess();
} else {
if (isViewPresent()) getView().onError();
}
}, err -> {
if (isViewPresent()) getView().onError();
});
}
/ *测试代码* /
@Test
public void testSending() throws Exception {
mController.sendSomething("", "");
assertFalse(mRepository.findAll().isEmpty()); // 1
verify(mController.getView(), atLeastOnce()).onSuccess(); // 2
}
由于在测试方法内部进行了线程化,我在第1行遇到了这个错误:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertFalse(Assert.java:64)
at org.junit.Assert.assertFalse(Assert.java:74)
这就在第2行:
Wanted but not invoked:
newInterface.onSuccess();
-> at com.example.MyTestClass.testSending
Actually, there were zero interactions with this mock.
我尝试过http://fedepaol.github.io/blog/2015/09/13/testing-rxjava-observables-subscriptions/解决方案,但对我而言,它无效。
我的验证应该检查是否调用了onSuccess()方法。但是这个方法在Observable.onSubscribe中,所以只有在订阅完成时才应该运行同步调用verify()。