0
私はAlarmManagerでアラームを起動し、BroadcastReceiverでそれを受け入れることをテストしようとしています。私はこれを見つけましたsources、そしてそこにすべてのことをやってください。放送受信機のAlarmManagerでBroadcastReceiverをテストする
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);
}
パーツ:
@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のラッパーです。しかし、それはまあまあと随時火災(20回の試行からのような1つの成功したテスト)動作します:
@Before public void setUp() throws Exception {
mQuestionNotificationReceiver = new QuestionNotificationReceiver();
mQuestions.registerReceiver(mQuestionNotificationReceiver,
new IntentFilter(QuestionNotificationReceiver.getAction(mQuestions)));
}
:またここに
@Inject RealmWrapper mRealmWrapper;
@Override public void onReceive(Context context, Intent intent) {
((Questions) context.getApplicationContext()).getQuestionNotificationReceiverComponent()
.inject(this);
onPostInjectReceive(context, intent);
}
は@Before方法であり、
コードがほぼ正しいと表示されることもありますが、非常にばかげています。私がカスタムRetryRule
を使用してテストが失敗した場合に再試行すると、Thread.sleep()が約10秒かかるため、テストは非常に長くなります。この状況をどう管理するか?
あなたがCalendar.HOURとCalendar.HOUR_OF_DAYの両方を使用し、それが目的でありますか? – joaonlima
@joaonlima hm、本当に、私は確認します、ありがとう! –
@joaonlima信じられないほど!答えを書く、私はそれを受け入れる:) –