Testing Notifications in Android

Gaganpreet picture Gaganpreet · Nov 3, 2015 · Viewed 10.1k times · Source

My android app has a service which sends notifications to user based on parameters like number of runs of the app. The notifications are sent at different times in different situations. I want to test whether notifications are sent at the right times in all the different cases. Does android provide a way of such a testing ?

Answer

Prem Choudhary picture Prem Choudhary · Feb 13, 2017

Testing Notification using UIAutomator:

Just go through the below code. It will help you in testing the notification.

UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.openNotification();
device.wait(Until.hasObject(By.text(NOTIFICATION_TITLE)), TIMEOUT);
UiObject2 title = device.findObject(By.text(NOTIFICATION_TITLE));
UiObject2 text = device.findObject(By.text(NOTIFICATION_TEXT));
assertEquals(NOTIFICATION_TITLE, title.getText());
assertEquals(NOTIFICATION_TEXT, text.getText());
title.click();
device.wait(Until.hasObject(By.text(ESPRESSO.getName())), TIMEOUT);

Don't forget to add the UIAutomator dependencies in build.gradle.

// UIAutomator dependency
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'