Parth
Parth

Reputation: 137

Test Notification messages in android using JUnit

I am writing JUnit test cases for my android application.

Here i need to verify notification functionality of my application. I can't find any way to doing this using JUnit.

Please share any ideas to verify the notification messages in android test application.

Upvotes: 1

Views: 162

Answers (1)

Jose Alcérreca
Jose Alcérreca

Reputation: 2048

If you really have to test notifications end to end, you can use UI Automator to open the notifications of the device and check that your notification is there.

For example:

import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.Until

@RunWith(AndroidJUnit4::class)
class NotificationTests {

    @get:Rule(order = 0)
    val composeTestRule = createAndroidComposeRule<YourActivity>()


    @Test
    fun checkNotificationWithUiAutomator() {
        // Do something to trigger the notification
        composeTestRule.onNodeWithTag("trigger").performClick()

        // Open notifications and check that the notification is there.
        val device = UiDevice.getInstance(getInstrumentation())
        device.openNotification()
        assert(device.wait(Until.hasObject(By.text("You have been notified")), 5000))
        device.pressBack() // Clean up
    }
}

Note that this wouldn't work with Robolectric end-to-end. However you can unit test it with shadows:

val notificationService = getInstrumentation().targetContext
            .getSystemService(NOTIFICATION_SERVICE) as NotificationManager

val manager = shadowOf(notificationService)
assertTrue(manager.allNotifications.size == 0)

showNotification(getInstrumentation().targetContext)
assertTrue(manager.allNotifications.size == 1)

Upvotes: 0

Related Questions