Testing Dialogs in Robolectric

AlertDialog.Builder(context)
.setMessage("Are you sure you want to delete this item?")
.setPositiveButton("Delete") { _, _ ->
viewModel.delete()
}
.setNegativeButton("Cancel") { _, _ -> }
.show()
// Press Delete button
activity.findViewById<View>(R.id.delete).performClick()
// Verify dialog appears with correct content
val dialog = ShadowDialog.getLatestDialog()
assertTrue(dialog.isShowing)
val rootView = dialog.findViewById<View>(android.R.id.message)
assertEquals(
"Are you sure you want to delete this item?",
dialog.findViewById<TextView>(android.R.id.message).text
)
dialog.findViewById<Button>(android.R.id.button2).performClick()
ShadowLooper.runUiThreadTasks()
assertFalse(dialog.isShowing)

Using the Espresso APIs to Test Dialogs in Robolectric

// Click the delete button
onView(withId(R.id.delete)).perform(click())
// Check that the dialog is shown and has valid content.
val dialog = ShadowDialog.getLatestDialog()
assertTrue(dialog.isShowing)
onView(withText("Are you sure you want to delete this item?"))
.inRoot(isDialog())
.check(matches(isDisplayed()))
// Click the cancel button and verify the dialog dismisses
onView(withText("Cancel"))
.inRoot(isDialog())
.perform(click())
ShadowLooper.runUiThreadTasks()
assertFalse(dialog.isShowing)

--

--

--

Documenting my learnings on my journey as a software engineer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

GloballyDynamic: Dynamic delivery during development

Avoid these mistakes in pubspec.yaml | Tips for Flutter beginners

Breaking the ice: Service Locator and Dependency Injection Which is What

isChecked vs. isSelected for Android CheckBoxes and RadioButtons

Complete learning path of Android

Image Segmentation in Android with Fritz AI

Android Jetpack Component Overview

Fritz AI in Flutter Applications

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brian Terczynski

Brian Terczynski

Documenting my learnings on my journey as a software engineer.

More from Medium

Sophixticated Joker

You could do this to improve your UI tests performance

Transformations in encapsulated LiveData

Two mistakes when I use AutoValue