浓缩咖啡:如果视图存在则返回布尔值 [英] Espresso: return boolean if view exists

查看:29
本文介绍了浓缩咖啡:如果视图存在则返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查 Espresso 是否显示了视图.这是一些伪代码来显示我正在尝试的内容:

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)).check(doesNotExist()){
   // then do something
 } else {
   // do nothing, or what have you
 }

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

But my problem is .check(doesNotExist()) does not return boolean. It is just an assertion. With UiAutomator I was able to just do something like so:

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

推荐答案

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

Conditional logic in tests is undesirable. With that in mind, Espresso's API was designed to guide the test author away from it (by being explicit with test actions and assertions).

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

Having said that, you can still achieve the above by implementing your own ViewAction and capturing the isDisplayed check (inside the perform method) into an AtomicBoolean.

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

Another less elegant option - catch the exception that gets thrown by failed check:

    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
    }

这篇关于浓缩咖啡:如果视图存在则返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆