0
我正在嘗試使用AlarmManager測試啓動警報並接受它與BroadcastReceiver。我發現了這個sources,並做了這樣的一切。但是,它的工作原理馬馬虎虎和火災不時(從20次嘗試像1測試成功):使用AlarmManager測試BroadcastReceiver
@Test public void testOnReceive_defaultAlarm_accepted() throws Exception {
final SharedPreferences sharedPrefs = mQuestions.getAppComponent().getSharedPrefs();
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() + TIME_DELAY_SNOOZE); // time for alarm
sharedPrefs.edit()
.putString(mQuestions.getString(R.string.pref_notification_time_key),
TimePreference.timeToString(calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE)))
.apply(); // set test prefs to alarm
QuestionNotificationUtils.launchDefaultAlarm(mQuestions, sharedPrefs); // launch alarm
Thread.sleep(TIME_DELAY_SNOOZE + TIME_DELAY); // wait for alarm to be fired
assertNotNull(mQuestionNotificationReceiver.mRealmWrapper); // check if injected, and HERE IT FAILS
verify(mQuestionNotificationReceiver.mRealmWrapper, times(1)).getQuestions(); // check if fired with Mockito
}
啓動默認的報警是解決此FUNC包裝:廣播接收器的
private static void launchAlarm(Context ctx, SharedPreferences prefs, int id) {
final AlarmManager alarmMgr = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
final PendingIntent alarmIntent =
PendingIntent.getBroadcast(ctx, id, QuestionNotificationReceiver.getIntent(ctx, id),
PendingIntent.FLAG_UPDATE_CURRENT);
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
final String time = prefs.getString(ctx.getString(R.string.pref_notification_time_key),
ctx.getString(R.string.questions_preference_fragment_default_notification_time));
calendar.set(Calendar.HOUR_OF_DAY, TimePreference.parseHour(time));
calendar.set(Calendar.MINUTE, TimePreference.parseMinute(time));
alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
alarmIntent);
}
配件:
@Inject RealmWrapper mRealmWrapper;
@Override public void onReceive(Context context, Intent intent) {
((Questions) context.getApplicationContext()).getQuestionNotificationReceiverComponent()
.inject(this);
onPostInjectReceive(context, intent);
}
另外這裏的@Before方法:
@Before public void setUp() throws Exception {
mQuestionNotificationReceiver = new QuestionNotificationReceiver();
mQuestions.registerReceiver(mQuestionNotificationReceiver,
new IntentFilter(QuestionNotificationReceiver.getAction(mQuestions)));
}
有時它的工作,它表明,代碼幾乎是正確的,但它非常片狀。如果我開始使用自定義RetryRule
重試測試,如果它失敗,測試變得很長,因爲Thread.sleep()大約需要10秒。如何管理這種情況?
您同時使用Calendar.HOUR和Calendar.HOUR_OF_DAY,是故意的? – joaonlima
@joaonlima嗯,真的,我會檢查,謝謝! –
@joaonlima令人難以置信!寫下答案,我會接受它:) –