Search code examples
androidandroid-studioandroid-uiautomatorandroid-espresso

How to use espresso to press a AlertDialog button


I want to press below button using Espresso, but I'm not sure how. Should I get the resource-id? Or how to set an ID to the AlertDialog??

enter image description here

@RunWith(AndroidJUnit4.class)
public class ApplicationTest {

@Rule
public ActivityTestRule<LoadingActivity> mActivityRule =
        new ActivityTestRule<>(LoadingActivity.class);

@Test
public void loginClickMarker() {
//Doesn't work:
    onView(withText("GA NAAR INSTELLINGEN")).perform(click());
}
}

public class PopupDialog {

public static void showGPSIsDisabled(Context context, String msg, final PopupDialogCallback popupDialogCallback) {
    new AlertDialog.Builder(context)
            .setTitle(context.getString(R.string.location_turned_off))
            .setMessage(msg)
            .setPositiveButton(context.getString(R.string.go_to_settings), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    popupDialogCallback.hasClicked();
                }
            }).show();
}
}

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "GA NAAR INSTELLINGEN"


Solution

  • According to StackOverflow similar issue: Check if a dialog is displayed with Espresso

    You should change your code from:

    onView(withText("GA NAAR INSTELLINGEN")).perform(click());
    

    to

    onView(withText("GA NAAR INSTELLINGEN"))
        .inRoot(isDialog())                 
        .check(matches(isDisplayed()))      
        .perform(click());  
                
    

    If it won't work, don't bother to use long with Espresso another great Google's instrumentation test called uiatomator.

    Check: http://qathread.blogspot.com/2015/05/espresso-uiautomator-perfect-tandem.html

    Example code:

    // Initialize UiDevice instance
    UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    
    // Search for correct button in the dialog.
    UiObject button = uiDevice.findObject(new UiSelector().text("GA NAAR INSTELLINGEN"));
    if (button.exists() && button.isEnabled()) {
        button.click();
    }