Espresso - How to check if one of the view is displayed

后端 未结 10 2012
心在旅途
心在旅途 2021-02-03 17:22

In my test, after one action, there are two possible views which can appear and both of them are correct. How can I check if one of the view is displayed. For a single view I ca

10条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 17:38

    It's possible to catch the exceptions raised by Espresso like this:

    If you want to test if a view is in hierarchy:

    try {
        onView(withText("Button")).perform(click());
        // View is in hierarchy
    
    } catch (NoMatchingViewException e) {
        // View is not in hierarchy
    }
    

    This exception will be thrown if the view is not in the hierarchy.

    Sometimes the view can be in the hierarchy, but we need to test if it is displayed, so there is another exception for assertions, like this:

    try {
        onView(withText("Button")).check(matches(isDisplayed()));
        // View is displayed
    } catch (AssertionFailedError e) {
        // View not displayed
    }
    

提交回复
热议问题