Android 开发 Espresso(查找视图)

Android 开发 Espresso(查找视图)

使用onView 查找视图

withId 匹配器

通过R.id查找

onView(withId(R.id.view));

R.id被多个视图共享的时候,此时会抛出类似异常AmbiguousViewMatcherException,异常信息会给你提供文字描述形式的当前视图结构,你可以搜索并找出所有使用非唯一 ​R.id​ 值的视图

还有NoMatchingViewException

java.lang.RuntimeException:
com.google.android.apps.common.testing.ui.espresso.AmbiguousViewMatcherException:
This matcher matches multiple views in the hierarchy: (withId: is <123456789>)
...

+----->SomeView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true,
is-focused=false, is-focusable=false, enabled=true, selected=false, is-layout-requested=false, text=, root-is-layout-requested=false, x=0.0, y=625.0, child-count=1}
****MATCHES****
|
+------>OtherView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true,
is-focused=false, is-focusable=true, enabled=true, selected=false, is-layout-requested=false, text=Hello!, root-is-layout-requested=false, x=0.0, y=0.0, child-count=1}
****MATCHES****

通过查看视图丰富的属性,你兴许可以找到唯一可确认的属性(上例中,其中一个视图有一个“Hello!”文本)。你可以通过使用组合匹配器结合该属性来缩小搜索范围:

onView(allOf(withId(R.id.view), withText("Hello!")));

你也可以使用 ​not​反转匹配:

onView(allOf(withId(R.id.my_view), not(withText("Unwanted"))));

你可以在 ViewMatchers 类中查看 Espresso 提供的视图匹配器。

如果目标视图在一个​AdapterView​(如 ​ListView​,​GridView​,​Spinner​)中,将不能使用 onView​方法,推荐使用​onData​ 方法。

使用onData()查找Adapter的view

我们还是使用官方的例子查找一下

使用Spinner 的adapter的 view

我们先打开spinner


然后我们找到其中一个item

 //点击打开Spinner
        ViewInteraction view = onView(withId(R.id.test_spinner));

        view.perform(click());

        //找到这个view  并点击
        onData(allOf(is(instanceOf(String.class)), is("item4")))
                .perform(click());

稍后我们介绍 Matchers

错误统计

因为还没有加载到这个item所以执行错误

dalvik.system.VMStack.getThreadStackTrace(Native Method)

解决方案

          //休眠再去找这个
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        item20.perform(scrollTo());

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容