Espresso: return boolean if view exists

前端 未结 8 1685
陌清茗
陌清茗 2020-12-09 01:23

I am trying to check to see if a view is displayed with Espresso. Here is some pseudo code to show what I am trying:

if (!Espresso.onView(withId(R.id.someID)         


        
相关标签:
8条回答
  • 2020-12-09 01:49

    We need that functionality and I ended up implementing it below:

    https://github.com/marcosdiez/espresso_clone

    if(onView(withText("click OK to Continue")).exists()){ 
        doSomething(); 
    } else { 
       doSomethingElse(); 
    }
    

    I hope it is useful for you.

    0 讨论(0)
  • 2020-12-09 01:50

    I think to mimic UIAutomator you can do this:
    (Though, I suggest rethinking your approach to have no conditions.)

    ViewInteraction view = onView(withBlah(...)); // supports .inRoot(...) as well
    if (exists(view)) {
         view.perform(...);
    }
    
    @CheckResult
    public static boolean exists(ViewInteraction interaction) {
        try {
            interaction.perform(new ViewAction() {
                @Override public Matcher<View> getConstraints() {
                    return any(View.class);
                }
                @Override public String getDescription() {
                    return "check for existence";
                }
                @Override public void perform(UiController uiController, View view) {
                    // no op, if this is run, then the execution will continue after .perform(...)
                }
            });
            return true;
        } catch (AmbiguousViewMatcherException ex) {
            // if there's any interaction later with the same matcher, that'll fail anyway
            return true; // we found more than one
        } catch (NoMatchingViewException ex) {
            return false;
        } catch (NoMatchingRootException ex) {
            // optional depending on what you think "exists" means
            return false;
        }
    }
    

    Also exists without branching can be implemented really simple:

    onView(withBlah()).check(exists()); // the opposite of doesNotExist()
    
    public static ViewAssertion exists() {
        return matches(anything());
    }
    

    Though most of the time it's worth checking for matches(isDisplayed()) anyway.

    0 讨论(0)
提交回复
热议问题