使用Espresso

时间:2016-08-19 09:21:11

标签: android listview android-espresso

我正在编写一个espresso测试,用于检查哪个未能在FooterView中找到我以编程方式添加到ListView中的TextView。在espresso测试中找到TextView的唯一方法是等待1秒后再检查是否TextView存在。

    // checks if the list view contains an issue that has the text "Do" somewhere
    onView(withId(R.id.listView)).check(matches(hasDescendant(withText(containsString("Do")))));
    // swipes down to access the load older issues button
    onView(allOf(withId(R.id.mainLayout))).perform(swipeUp());

    // View listView = shelfActivity.getActivity().findViewById(R.id.listView_footer_textview); // returns the view, even when espresso tells that it does not exist
    // Thread.sleep(1000); // need to wait in order to find the footerview of the list view

    // check if the load older issues button is here
    onView(allOf(withId(R.id.listView_footer_textview), isDisplayed())).check(matches(isDisplayed()));

FooterView中的这个TextView实际上是存在的,我可以在同一个地方的测试中找到它,如果我尝试用普通的findById()方法得到它,但是当我用浓咖啡检查时却找不到它。

所以我的问题是: 如果我想在FooterView中检查TextView,我是否真的必须调用Thread.sleep(1000)来传递测试。对我来说,浓缩咖啡的巨大优势在于,我不需要等待视图准备就绪,所以现有的浓缩咖啡功能是否自动完成?

1 个答案:

答案 0 :(得分:0)

您可以通过ListView方法找到onData的FooterView。

这是official documents

  

例如:

public static final String FOOTER = "FOOTER";
...
View footerView = layoutInflater.inflate(R.layout.list_item, listView, false);
((TextView) footerView.findViewById(R.id.item_content)).setText("count:");
((TextView) footerView.findViewById(R.id.item_size)).setText(String.valueOf(data.size()));
listView.addFooterView(footerView, FOOTER, true);
     

然后,您可以编写匹配此对象的匹配器:

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

@SuppressWarnings("unchecked")
public static Matcher<Object> isFooter() {
  return allOf(is(instanceOf(String.class)), is(LongListActivity.FOOTER));
}
     

在测试中加载视图是微不足道的:

import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;
import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
import static com.google.android.apps.common.testing.ui.espresso.sample.LongListMatchers.isFooter;

public void testClickFooter() {
  onData(isFooter())
    .perform(click());
  ...
}