9

I want to be able to test some code that adds pending intents to the Alarm Manager but while I can create my own mock context to return it from getSystemService() I can't create my own sub class of Alarm Manager due to it having a private constructor.

Would there be another (better?) way for me to be able to test that my code correctly is adding (or not) alarms based on my test pre conditions?

MBMJ
  • 5,323
  • 8
  • 32
  • 51
Maks
  • 7,562
  • 6
  • 43
  • 65
  • I usually go into settings on my device and manually jump the date forward to trigger the alarm. – FoamyGuy Aug 06 '12 at 02:36
  • I want to be able to run the tests automatically, but that's an interesting idea... I could change try changing the system time forward (testing on the emulator) and test to see if the pending intents fire. – Maks Aug 06 '12 at 02:38

1 Answers1

14

Two things I can think of that might help:

  1. for checking the alarm has been scheduled manually

    adb shell dumpsys alarm | grep com.your.package

  2. for checking there is an alarm set in code you can use Robolectric shadows. Here's an example of it being used: http://www.multunus.com/blog/2014/03/tdd-android-using-robolectric-part-3/

You could use (from the article):

@RunWith(RobolectricTestRunner.class)
public class ResetAlarmTest {
    ShadowAlarmManager shadowAlarmManager;
    AlarmManager alarmManager;

    @Before
    public void setUp() {
       alarmManager = (AlarmManager) Robolectric.application.getSystemService(Context.ALARM_SERVICE);
       shadowAlarmManager = Robolectric.shadowOf(alarmManager);
    }

    @Test
    public void start_shouldSetRepeatedAlarmWithAlarmManager() {
        Assert.assertNull(shadowAlarmManager.getNextScheduledAlarm());
        new ResetAlarm(Robolectric.application.getApplicationContext());
        ScheduledAlarm repeatingAlarm = shadowAlarmManager.getNextScheduledAlarm();
        Assert.assertNotNull(repeatingAlarm);
    }
}
Ben Pearson
  • 7,532
  • 4
  • 30
  • 50
  • 1
    Upvote for the very useful link to Roboelectrics shadows, though they can't quite solve my problem here as far as I can see? – Maks Nov 10 '14 at 21:42
  • Unless I misunderstood your question, the second link had some quite good examples of testing for the next alarm by shadowing alarm manager which should help. I've updated the answer with a relevant code snippet from the aforementioned article. – Ben Pearson Nov 11 '14 at 09:05