Unit test: check if the alarm has been canceled

I am writing unit tests for my application and I want to test if the alarm is canceled correctly, but I cannot find the correct solution for this. I am familiar with the method of checking if an alarm is active using the PendingIntent.getBroadcast () parameter with the FLAG_NO_CREATE flag.

I was able to successfully reuse the getBroadcast () function in one test, first checking to see if the alarm was set when the app was started and then later to check if the alarm was set, both times return expected booleans.

      public void testTimerButtonStartProcess(){

      Intent intent = new Intent (appContext, OnAlarmReceiver.class);
      intent.putExtra(Scheduler.PERIOD_TYPE, 1);
      intent.putExtra(Scheduler.DELAY_COUNT, 0);
      intent.setAction(Scheduler.CUSTOM_INTENT_ALARM_PERIOD_END);
      boolean alarmUp = (PendingIntent.getBroadcast(appContext, 0, intent,PendingIntent.FLAG_NO_CREATE) != null);

      assertFalse("the alarm manager wasnt running when app is lauched", alarmUp);

      solo.clickOnView(timerLayout);
      instr.waitForIdleSync();
      solo.sleep(5000);
      alarmUp = (PendingIntent.getBroadcast(appContext, 0, intent,PendingIntent.FLAG_NO_CREATE) != null);
      assertTrue("the alarm is set", alarmUp);


  }

      

But when I try to do it in reverse order (first by checking if the alarm is set and then if it is no longer set), my test fails because after the second check (when the alarm should be canceled) getBroadcast () returned true ( i expected to get false).

      public void testTimerButtonLongPress(){

      solo.clickOnView(timerLayout);
      instr.waitForIdleSync();
      Intent intent = new Intent (appContext, OnAlarmReceiver.class);
      intent.putExtra(Scheduler.PERIOD_TYPE, 1);
      intent.putExtra(Scheduler.DELAY_COUNT, 0);
      intent.setAction(Scheduler.CUSTOM_INTENT_ALARM_PERIOD_END);
      boolean alarmUp = (PendingIntent.getBroadcast(appContext, 0, intent,PendingIntent.FLAG_NO_CREATE) != null);         
      assertTrue("the alarm manager is running", alarmUp);
      solo.clickLongOnView(timerLayout, 1500);
      instr.waitForIdleSync();
      solo.sleep(3000);
      alarmUp = (PendingIntent.getBroadcast(appContext, 0, intent,PendingIntent.FLAG_NO_CREATE) != null);
      assertFalse("the alarm manager was not running anymore", alarmUp);

  }

      

I also tried using getBroadcast only once after the app canceled the alarm, but I got true anyway.

In the meantime, I'm pretty sure canceling the alarm works as expected, because the app stops alarming after it's "turned off".

+3


source to share





All Articles