Android Espresso - Wait until dialog is displayed

Viewed 711

What are the possible ways to write tests to wait for a dialog, should support both dialogFragment and Dialog(AlertDialog) ?.

1 Answers

This is how I was able to figure out, posting sample code may help others. The idea is keep periodically checking until real timeout happens.

public static void waitForDialogWithText(String text, long timeout) {
    waitForDialog(withText(text), timeout);
}

private static void waitForDialog(Matcher<View> viewMatcher, long timeout) {
    final long endTime = System.currentTimeMillis() + timeout;
    Exception exception = null;
    while (System.currentTimeMillis() < endTime) {
        try {
            // wait for x second // Thread.sleep(x mills)
            onView(viewMatcher).check(matches(isDisplayed()));
            return;
        } catch (Exception e) {
            exception = e;
        }
    }
    if (exception != null) {
        throw new RuntimeException(exception.getMessage());
    }
}
Related