Espresso check if no dialog is displayed

风流意气都作罢 提交于 2021-01-22 06:55:11

问题


I have a method that checks several conditions, and calls another activity when they are satisfied. When a condition isn't satisfied, it should display an error dialog (which is currently using a DialogFragment to display an alert dialog). The method looks something like this:

void checkAndCall() {
    CustomObject o1 = null;
    try {
        o1 = CustomObject.parse(editText1.getText().toString());
    } catch (CustomException e) {
        handleBadCase(e);
        return;
    }

    CustomObject o2 = null;
    try {
        o2 = CustomObject.parse(editText2.getText().toString());
    } catch (CustomException e) {
        handleBadCase(e);
        return;
    }

    callOtherActivity();
}

Unfortunately, I had forgotten a return statement, which caused the method to drop to the next check (which failed) and display two error dialogs. I want to make sure that this doesn't happen again, so have written a test for it.

My test looks like this:

public class TestClass {

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

    @Test
    public void onlyOneDialogAppearsWithEmptySolve() {
        /* Hit solve with no text entered */
        onView(withId(R.id.solve_button)).perform(click());

        /* Check that dialog is displayed */
        onView(isRoot()).inRoot(isDialog()).check(matches(isDisplayed()));

        /* Press cancel */
        onView(withText(getString(R.string.cancel))).perform(click());

        /* No dialog is displayed */
        onView(isRoot()).inRoot(isDialog()).check(doesNotExist());      
    }
} 

I had thought that onView(isRoot()).inRoot(isDialog()) would match the root view of any dialog. However, this seems to just hang if it doesn't match anything. Thus, when the test should be satisfied (only one dialog appears and is cancelled), it hangs. If we comment out that line, and do not display any dialogs, the test hangs on the Check that dialog is displayed line.

I would prefer not to match against dialog text, as they may all be different. I still need to be sure that only one occurs if any do. Right now, I am taking advantage of all of them having a "Cancel" button to match against. However, I would prefer to not rely on this.

Is there a method for saying Is any dialog displayed? and Are no dialogs displayed? Why do the checks that I have cause this hanging?

来源:https://stackoverflow.com/questions/48960164/espresso-check-if-no-dialog-is-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!