hyung jun yoo
hyung jun yoo

Reputation: 613

Espresso, Find dialog and dismiss it

I tried to find a dialog cancel button and push it in Espresso UI Testing, but I couldn't.

This is my code.

onView(withId(R.id.dialog_close_button)).check(matches(isDisplayed()))

What is the best solution for it?

Please comment your opinion.

Upvotes: 2

Views: 2646

Answers (3)

jeprubio
jeprubio

Reputation: 18002

You should add the RootMatcher isDialog() to match Roots that are dialogs (i.e. is not a window of the currently resumed activity).

And also don't forget to perform click on that button if you want to dismiss the dialog as you said in the title.

Use this code:

onView(withId(R.id.dialog_close_button))
    .inRoot(isDialog())
    .check(matches(isDisplayed()))
    .perform(click());

Upvotes: 1

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20616

If it's an Android dialog and you use two buttons you can find the view using:

onView.withId(android.R.id.button1).perform(ViewActions.click()) //Click on accept button
onView.withId(android.R.id.button2).perform(ViewActions.click()) //Click on cancel button

If you want to test if they are visible you want to use:

assert onView.withId(android.R.id.button1).check(matches(ViewMatchers.isDisplayed()))

Then if you don't want the android one, just replace the id's for yours and it should work, remember if you have duplicated ID's it will complain

EDIT

I suggest to use Layout Inspector, so you can find the ID of each component of your screen so you can replace it with the old answer.

So the steps are :

  1. Open the app and find that dialog
  2. Then go to Tools > Layout Inspector > Choose your processor
  3. Click on the item you want to click with Espresso
  4. Replace it in your onView.withId(HERE_GOES_THE_ID)...

Upvotes: 1

hyung jun yoo
hyung jun yoo

Reputation: 613

If you use the UI-Automator with AndroidX, you can find the dialog and buttons.

It is a gradle dependency code.

dependencies {
    androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}

You can reach the button with this code.

It is Kotlin code.

val cancel = activityTestRule.activity.getString(R.string.dialog_cancel_button)
val button = UiDevice
    .getInstance(InstrumentationRegistry.getInstrumentation())
    .findObject(
        UiSelector()
            .text(cancel.toUpperCase())
            .text(cancel)
    )
if (button.exists() && button.isEnabled) {
    button.click()
}

Upvotes: 2

Related Questions