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?
Two things I can think of that might help:
for checking the alarm has been scheduled manually
adb shell dumpsys alarm | grep com.your.package
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With