美文网首页
Android 开发 Espresso(查找视图)

Android 开发 Espresso(查找视图)

作者: TiaoPi | 来源:发表于2018-10-24 16:29 被阅读4次

    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());
    
    

    相关文章

      网友评论

          本文标题: Android 开发 Espresso(查找视图)

          本文链接:https://www.haomeiwen.com/subject/qodrbxtx.html