AndroidKotlinTestingTutorials

Testing Notifications in Android UI tests

Android UI testing can be a little tricky sometimes. Testing notifications displayed from your application may not seem very straightforward. You may ask yourself – How am I supposed to interact with status bar or display notifications panel? Well, the answer is simple – use UIAutomator.

UIAutomator is a framework which allows you to interact with your app and system apps. I am not going describe all of its capabilities now. Instead let’s get down to the point of this article. If you want to learn more about UIAutomator, visit official android documentation.

To test notifications, first of all add UIAutomator as a dependency to your gradle.settings file.

androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'

Now, in the UI test case trigger a notification from you app and check if the notification was displayed.

@Test
fun testNotifications() {
   // 1. Display notification. This line(s) will change depending on you app implementation.  
   val title = "Notifications title"
   NotificationHelper.showNotification(title) 

   // 2. Get an object to interact with device which the tests are run on 
   val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
  
   // 3. Show notifications panel
   device.openNotification()

   // 4. Check if notification is displayed
   val timeout = 5000
   device.wait(Until.hasObject(By.text(title)), timeout)
   val displayedTitle = device.findObject(By.text(title))
   assertEquals(title, displayedTitle.text)
}

Since we might want to test multiple notifications with different titles and content, it’s a good idea to extract a function which will do just this.

fun assertNotificationDisplayed(title: String, content: String? = null, timeout: Long = 5000) {
   val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
   device.openNotification()

   device.wait(Until.hasObject(By.text(title)), timeout)
   val displayedTitle = device.findObject(By.text(title))
   assertEquals(title, displayedTitle.text)

   if (content != null) {
       val displayedText = device.findObject(By.text(content))
       assertEquals(content, displayedText.text)
   }
}

This way we got a very clean way for notifications testing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.