我得到了一个NullPointerException
测试方法shouldFetchMachineSettings()
。通过调试,我意识到控件没有进入可观察对象的成功回调,并且没有启动意图。因此例外。我意识到问题出在使用AndroidSchedulers.mainThread();
但无法找到解决方案。
机器设置.java
public class MachineSettings {
public static void fetch(final FragmentActivity activity,
MachineService machineService,
final ProgressDialog progressDialog) {
Observable zippedCalls = Observable.zip(
machineService.getSettings(),
machineService.getInfoAsObservable(),
machineService.getSupportedLanguages(),
new Func3() {
@Override
public Object call(final Object response1,
final Object response2,
final Object response3) {
return new HashMap<String, Object>() {{
put(MACHINE_SETTINGS, response1);
put(MACHINE_SETTINGS_INFO, response2);
put(MACHINE_SETTINGS_LANGUAGES, response3);
}};
}
});
zippedCalls.subscribeOn(getNewThread())
.observeOn(getAndroidSchedulerMainThread())
.subscribe(onSuccess(activity, progressDialog)
, onError(activity, progressDialog));
}
public static Scheduler getAndroidSchedulerMainThread() {
return AndroidSchedulers.mainThread();
}
public static Scheduler getNewThread() {
return Schedulers.newThread();
}
private static Action1 onSuccess(final FragmentActivity activity,
final ProgressDialog progressDialog) {
return new Action1() {
@Override
public void call(Object o) {
Intent intent = new Intent(activity, MachineSettingsActivity_.class);
// do some action using object o
activity.startActivity(intent);
}
};
}
private static Action1<Throwable> onError(final FragmentActivity activity,
final ProgressDialog progressDialog) {
return new Action1<Throwable>() {
@Override
public void call(Throwable error) {
// do some action
}
};
}
}
来自 MachineDetailsFragment.java 的调用
if (item.getItemId() == R.id.action_machine_settings) {
setupProgressDialog();
MachineSettings.fetch(getActivity(), machineService, progressDialog);
}
在 MachineDetailsFragmentTest.java 中进行测试
@Test
public void shouldFetchMachineSettings() {
MenuItem mockMenuItem = mock(MenuItem.class);
when(mockMenuItem.getItemId()).thenReturn(R.id.action_machine_settings);
Map<String, Integer> settings = new HashMap() {{put("privacy", 0);}};
Map<String, Integer> languages = new HashMap() {{put("index_0", 2);}} ;
Map<String, String> info = new HashMap() {{put("version", "1");}};
Observable<Map<String, Integer>> mockSupportedLanguages = Observable.just(languages);
Observable<Map<String, Integer>> mockSettings = Observable.just(settings);
Observable<Map<String, String>> mockInfo = Observable.just(info);
when(machineService.getSupportedLanguages()).thenReturn(mockSupportedLanguages);
when(machineService.getSettings()).thenReturn(mockSettings);
when(machineService.getInfoAsObservable()).thenReturn(mockInfo);
machineDetailFragment.onOptionsItemSelected(mockMenuItem);
Intent intent = Shadows.shadowOf(activity).peekNextStartedActivity();
assertThat(intent.getComponent().getClassName(),
is(MachineSettingsActivity_.class.getCanonicalName()));