Espresso 自动化测试(五)- onData() 的使用1
在之前的文章中,我们简单介绍了Espresso的使用。通过onView()方法我们可以快速定位到界面上我们需要测试的目标元素。onView()比较适用于UI比较简单的情况,在不需要过于复杂的匹配条件的情况下是很方便的。但是,对于类似ListView这种有UI复用的元素来说,只是通过onView()就显得复杂了一点。其实我们看看onView的备注就知道来。
/**
* Creates a {@link ViewInteraction} for a given view. Note: the view has
* to be part of the view hierarchy. This may not be the case if it is rendered as part of
* an AdapterView (e.g. ListView). If this is the case, use Espresso.onData to load the view
* first.
*
* @param viewMatcher used to select the view.
*
* @see #onData(org.hamcrest.Matcher)
*/
// TODO change parameter to type to Matcher<? extends View> which currently causes Dagger issues
public static ViewInteraction onView(final Matcher<View> viewMatcher) {
return BASE.plus(new ViewInteractionModule(viewMatcher)).viewInteraction();
}
其实上面就已经说明了在AdapaterView的情况下,需要使用onData来进行加载视图
AdapterView
AdapterView是一种通过Adapter来动态加载数据的界面元素。我们常用的ListView, GridView, Spinner等等都属于AdapterView。不同于我们之前提到的静态的控件,AdapterView在加载数据时,可能只有一部分显示在了屏幕上,对于没有显示在屏幕上的那部分数据,我们通过onView()是没有办法找到的。
对于AdapterView,Espresso 提供了如下的方法
/**
* Creates an {@link DataInteraction} for a data object displayed by the application. Use this
* method to load (into the view hierarchy) items from AdapterView widgets (e.g. ListView).
*
* @param dataMatcher a matcher used to find the data object.
*/
public static DataInteraction onData(Matcher<Object> dataMatcher) {
return new DataInteraction(dataMatcher);
}
我们研究一下这个方法的入参。从以上定义看出,该方法接收了一个Matcher
栗子
以上是一个简单的Spinner,点击对应的item后,界面下方的TextView会显示所选择的Item的内容。如下:
Adapter的实现如下:
new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.europe_countries)))
现在我需要选择界面未显示的选项 monaco. 并且验证选中后textview的内容是否正确
//点击spinner
onView(withId(R.id.countries_spinner)).perform(click());
//点击adpaterviewer中类型为String 并且内容为Monaco的文本,
onData(allOf(is(instanceOf(String.class)),is("Monaco"))).perform(click());
//验证文本的内容
onView(withId(R.id.country_label)).check(matches(withText("Monaco")));
以上只是一个简单的栗子,但是在实际我们项目中,我们的ListView的内容不可能只是一个简单的字符串,更多的是一个类的对象或者是一个map的形式进行存储的我们再来看看对于复杂的类型,又应该如何去实现点击以及验证呢?
我们在下一章再来详细说明下。
结束语
Espresso 难点确实在adapterView处。