当我使用 RxAndroid 和.observeOn(AndroidSchedulers.mainThread())
, 并使用 Android Studio 在模拟器上运行测试时,整个测试运行崩溃:
由于“
java.lang.NoSuchMethodError
” ,检测运行失败
并logcat
输出如下:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:54)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodError: rx.internal.schedulers.ScheduledAction.lazySet
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:46)
... 9 more
Error in app net.tbmcv.rxtest running instrumentation ComponentInfo{net.tbmcv.rxtest.test/android.test.InstrumentationTestRunner}:
java.lang.NoSuchMethodError
java.lang.NoSuchMethodError: rx.internal.schedulers.ScheduledAction.lazySet
Force stopping package net.tbmcv.rxtest uid=10042
Android Studio 和logcat
输出都没有提到我的项目或测试中的任何代码行。以下是我创建的重现此崩溃的简短示例项目的一些相关部分:
app/build.gradle
dependencies {
compile 'io.reactivex:rxandroid:0.24.0'
}
MainActivity.java
public class MainActivity extends Activity {
public void setTitleFrom(Observable<String> observable) {
observable.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
setTitle(s);
}
});
}
}
MainActivityFuncTest.java
public class MainActivityFuncTest extends ActivityInstrumentationTestCase2<MainActivity> {
public void testSetTitle() {
final String newTitle = "Hello World";
getActivity().setTitleFrom(Observable.just(newTitle));
getInstrumentation().waitForIdleSync();
assertEquals(newTitle, getActivity().getTitle());
}
}
如果我将MainActivity
代码修改为不使用,我的测试将正确运行observeOn()
:
public void setTitleFrom(Observable<String> observable) {
observable.subscribe(new Action1<String>() {
@Override
public void call(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setTitle(s);
}
});
}
});
}
但我宁愿使用observeOn()
,因为它更干净,更模块化。我怎样才能让我的测试运行?
我的模拟器正在运行 API 版本 8 (Android 2.2)。