Espresso 常用方法简介

来源:互联网 发布:黑马java课程表 编辑:程序博客网 时间:2024/06/05 02:22

最近在搞UT的东西,初步了解了espresso的一些基础的用法,下面简单介绍一下。
Espresso的环境搭建暂不介绍,戳链接Espresso环境搭建


1、获取控件ViewInteraction。
onView()可以通过控件的id获取对象,可以通过文本获取对象,可以根据多个条件获取对象,如:

onView(withId(R.id.view_id));onView(withText("Hello World!"));onView(allOf(withId(R.id.tv_label), withText("Hello")));

allOf方法中可以有多个判断条件,一般在id或者文本又重复的时候可以使用。

withText()方法中也可以用startsWith()、endsWith()等添加查找条件,方法用途顾名思义。如:

onView(allOf(withId(R.id.tv_label),withText(startsWith("Hello World"))))onView(allOf(withId(R.id.my_view), not(withText("Hello World"))))

注意:withId、withText等都是ViewMatchers的方法,这里静态import了,写的简单点。


2、ViewInteraction控件的操作。
主要通过perform()实现。如:

onView(allOf(withId(R.id.tv_label),withText(startsWith("Hello World")))).perform(click())

click() 点击操作。
perform()方法中的其它常见操作:typeText()在控件中输入内容、scrollTo()滑动到控件、clearText()清除文本等等


3、控件的UI验证 check()。
例如匹配文本:

onView(withId(R.id.tv_label)).check(matches(withText("Hello")));

控件是否显示:

onView(withText("备注")).check(matches(isDisplayed()));

上面是一些基本的test方法,想具体了解的童鞋戳这里

在实际test中,如果需要对popupwindow或者toast文本进行校验的时候,ViewInteraction提供了inRoot()方法,指定查找的ViewInteraction的rootView,用于区别查找,eg:

onView(withText("test"))              .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))                .check(matches(isDisplayed()));

先写到这里,后续会有更新。大神路过留下脚印哦

1 0
原创粉丝点击