Espresso 自动化测试(二)- 简单入门
介绍
我们先看看下面这张图
找某些东西
Espresso 提供了onView() 方法用来查看UI上指定的元素,该方法如下:
public static ViewInteraction onView(final Matcher<View> viewMatcher) {}
该方法接受一个 Matcher 类型的参数并且返回一个ViewInteraction 的对象,这里的matcher 是使用了一个hamcrest的测试框架,它提供了一套通用的匹配符matcher,并且我们还可以去自定义matcher。具体可以去这里了解下。其实onView就可以理解成通过一个指定的条件在当前的UI界面查找符合条件的View,并且将该View返回回来。
例如:
onView(withId(id));
我现在要找一个R.id为指定id的控件,那么我就从我的这个id出发,先生成一个查找匹配条件:withId(id)。然后把这个条件传给onView()方法:onView(withId(id)),让onView()方法根据这个条件找到我们想要的那个控件!
Espresso 提供了很多的方法,具体可以看上边图片中的view matchers。
还是上面的例子,有时候id这个值在多个视图中都被使用了,这个时候当你再试图去使用这个id的时候,系统就会报一个AmbiguousViewMatcherException的异常了。这个异常信息会以文本的形式提供当前视图的层次结构。让你查看到你查找的id值并不是唯一的
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****
所以你可能需要找到一些唯一的属性来查找对应的控件,如:
onView(allOf(withId(R.id.my_view), withText("Hello!")))
或者:
onView(allOf(withId(R.id.my_view), not(withText("Unwanted"))))
做某些事情
Espresso提供了如下方法来对相应的元素做操作:
public ViewInteraction perform(final ViewAction... viewActions) {}
perform 是ViewInteraction类中的方法, 还记得onView()方法的返回值么?yes,正是一个ViewInteraction对象。因此,我们可以在onView()方法找到的元素上直接调用perform()方法进行一系列操作:
onView(...).perform(click());
当然你还可以执行多个操作在一个perform中类似于:
onView(...).perform(typeText("Hello"), click());
检查某些东西
接下来我们需要检查一下这些操作的结果是否符合我们的预期了。
Espresso提供了一个check()方法用来检测结果:
public ViewInteraction check(final ViewAssertion viewAssert) {}
该方法接收了一个ViewAssertion的入参,该入参的作用就是检查结果是否符合我们的预期。一般来说,我们可以调用如下的方法来自定义一个ViewAssertion:
public static ViewAssertion matches(final Matcher<? super View> viewMatcher) {}
例如:检查一个视图的文本是否有 hello
onView(...).check(matches(withText("hello")));
注意:不要把你要”assertions“的内容放到onView的参数中,相反的你应该清楚的在你的检查处说明你需要检查哪些内容如:
onView(allOf(withId(...), withText("Hello!"))).check(matches(isDisplayed()));
结束
好了,如果说你看明白了上面的内容的话,那么你基本就算对Espresso入门了。!