意式浓缩咖啡:如果视图存在,则返回布尔值

我正在尝试检查是否使用Espresso显示视图。下面是一些伪代码来显示我正在尝试的内容:

if (!Espresso.onView(withId(R.id.someID)).check(doesNotExist()){
   // then do something
 } else {
   // do nothing, or what have you
 }

但我的问题是不返回布尔值。这只是一个断言。使用UiAutomator,我能够做这样的事情:.check(doesNotExist())

 if (UiAutomator.getbyId(SomeId).exists()){
      .....
   }

答案 1

测试中的条件逻辑是不可取的。考虑到这一点,Espresso的API旨在引导测试作者远离它(通过显式测试操作和断言)。

话虽如此,您仍然可以通过实现自己的ViewAction并将isDisplayed检查(在执行方法内部)捕获到AtomicBootes中来实现上述目标。

另一个不太优雅的选项 - 捕获由失败的检查引发的异常:

    try {
        onView(withText("my button")).check(matches(isDisplayed()));
        //view is displayed logic
    } catch (NoMatchingViewException e) {
        //view not displayed logic
    }

具有扩展函数的 Kotlin 版本:

    fun ViewInteraction.isDisplayed(): Boolean {
        try {
            check(matches(ViewMatchers.isDisplayed()))
            return true
        } catch (e: NoMatchingViewException) {
            return false
        }
    }

    if(onView(withText("my button")).isDisplayed()) {
        //view is displayed logic
    } else {
        //view not displayed logic
    }

答案 2

我认为要模仿UIAutomator,你可以这样做:
不过,我建议重新考虑你的方法,没有条件。)

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;
    }
}

同样没有分支也可以实现非常简单:exists

onView(withBlah()).check(exists()); // the opposite of doesNotExist()

public static ViewAssertion exists() {
    return matches(anything());
}

虽然大多数时候无论如何都值得检查。matches(isDisplayed())


推荐