Я столкнулся с проблемой в IntentFilter во время теста с использованием Mockito.Вот мой тестовый пример:
@Test
public void shouldBeAbleToObserveBattery(){
Disposable disposable = ReactiveBattery.observeBatteryChanges(mContext).subscribe(batteryState ->{
assertThat(batteryState.level(), is(not(-1)));
assertThat(batteryState.plugged(), is(not(-1)));
assertThat(batteryState.scale(), is(not(-1)));
});
}
Метод PresenterClass:
@Override
public void observeBattery() {
getCompositeDisposable().add(ReactiveBattery
.observeBatteryChanges(getContext())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(state -> getBaseView().onBatteryChanged(state)));
}
observeBatteryChanges
и receiver
:
@Override
public Observable<BatteryState> observeBatteryChanges(final Context context) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryReceiver = createBatteryChangesReceiver(batterySubject);
context.registerReceiver(batteryReceiver, filter);
return batterySubject.toFlowable(BackpressureStrategy.LATEST)
.doOnCancel(() -> tryToUnregisterReceiver(context, batteryReceiver))
.distinctUntilChanged()
.toObservable();
}
@NonNull
private BroadcastReceiver createBatteryChangesReceiver(
final PublishSubject<BatteryState> subject) {
return new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
subject.onNext(BatteryState.create(level, scale, plugged, BatteryStatus.of(status)));
}
};
}
Когда я запускаюпроверить наличие ошибки в строке final IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
java.lang.RuntimeException: Stub!
at android.content.IntentFilter.<init>(IntentFilter.java:144)
Как можно посмеяться над этим IntentFilter и BroadcastReceiver для решения этой проблемы?Поскольку я новичок в этом тестировании на Мокито, ожидаю помощи.