Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mock AlarmManager for testing

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?

like image 870
Maks Avatar asked Aug 06 '12 02:08

Maks


1 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);
    }
}
like image 122
Ben Pearson Avatar answered Oct 21 '22 00:10

Ben Pearson