2016-09-24 57 views
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秒。如何管理这种情况?

+0

您同时使用Calendar.HOUR和Calendar.HOUR_OF_DAY,是故意的? – joaonlima

+0

@joaonlima嗯,真的,我会检查,谢谢! –

+1

@joaonlima令人难以置信!写下答案,我会接受它:) –

回答

1

二者必选其一Calendar.HOUR或Calendar.HOUR_OF_DAY,但不能同时

相关问题