Home » Android » android – Creating a mock AlarmManager for testing

android – Creating a mock AlarmManager for testing

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&Answers:

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);
    }
}