我有一个带有NavigationDrawer
的应用程序。我想测试是否使用Espresso在NavigationDrawer的列表中选择了正确的项目。
我找到了一种在列表视图中单击项目的方法。我使用了同样的方法来测试列表项是否被选中。但这种行为很奇怪:第一次通话似乎有效,但第二次通话却无效。你知道是什么原因造成的吗,或者我该怎么做得更好?
我试过这个:
// Open drawer.
openDrawer(DRAWER_LAYOUT_ID);
// We expect that the first item (map overview) is selected.
// Here it works fine. The check succeeds.
String mapOverviewTitle = mActivity.getString(R.string.map_overview);
onView(allOf(withId(R.id.title), hasSibling(withText(mapOverviewTitle))))
.check(matches(isSelected()));
// Navigate to the login fragment. This works fine too.
openDrawer(DRAWER_LAYOUT_ID);
String loginTitle = mActivity.getString(R.string.login);
onView(allOf(withId(R.id.title), hasSibling(withText(loginTitle))))
.perform(click());
// We expect that the login item is selected.
openDrawer(DRAWER_LAYOUT_ID);
// This does not work. The check fails.
onView(allOf(withId(R.id.title), hasSibling(withText(loginTitle))))
.check(matches(isSelected()));
closeDrawer(DRAWER_LAYOUT_ID);
我从第二次通话中得到的错误信息是:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'is selected' doesn't match the selected view.
Expected: is selected
Got: "AppCompatTextView{id=2131558468, res-name=title, visibility=VISIBLE, width=240, height=48, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=72.0, y=8.0, text=Login, input-type=0, ime-target=false, has-links=false}"
看起来您需要构建一个自定义视图匹配器。您可以在这里查看inRoot()
方法的示例,该方法将允许您选择与哪个窗口层交互。您的测试当前正在与最顶层的textView交互,您希望在此之前与层交互一级,并确保您的更改已启动。
https://code.google.com/p/android-test-kit/source/browse/testapp_test/src/main/java/com/google/android/apps/common/testing/ui/testapp/MultipleWindowTest.java
为什么不通过onNavigationDrawerItemSelected(int position)
方法执行代码,如下所示:
public void onNavigationDrawerItemSelected(int position) {
Fragment frag = Dialer.newInstance("uselessParam1", "uselessParam2");
switch (position){
case 0:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}
}
您只需看到哪个值与您想要的列表项相匹配。
在我的情况下,我是这样做的:
String fragmentTitle = mInstrumentation.getTargetContext().getString(TITLE_STRING_ID);
openDrawer(DRAWER_LAYOUT_ID);
onView(withText(fragmentTitle)).perform(click());
onView(withId(R.id.toolbar_title)).check(matches(withText(fragmentTitle)));
如果你有一个工具栏,里面有一个文本视图工具栏标题,你可以这样检查它。