android - Espresso : check if NavigationDrawer list item is selected

标签 android navigation-drawer android-testing android-espresso

我有一个带有 NavigationDrawer 的应用程序。我想使用 Espresso 测试是否在 NavigationDrawer 的列表中选择了正确的项目。

我找到了一种在 ListView 中点击项目的方法。我使用相同的方法来测试列表项是否被选中。但行为很奇怪:第一次调用似乎有效,但第二次调用无效。知道是什么原因导致的,或者我如何才能做得更好?

我试过这个:

// 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}"

最佳答案

看来您需要构建自定义 View 匹配器。您可以在此处查看 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

关于android - Espresso : check if NavigationDrawer list item is selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135157/

相关文章:

android - 如何将 Android SingleLaunchActivityTestCase 转换为 ActivityTestRule? (仪器仪表单元测试)

android-fragments - 无法解析androidx.fragment的依赖项:fragment-testing

java - 允许非 ssl 连接 : javax.net.ssl.SSLHandshakeException: 握手失败

java - recyclerview 项目显示抽屉导航 fragment 中显示空白屏幕

android - 从分水岭蒙版中删除白色背景图像

android - 抽屉导航 : text is hidden below actionbar?

java - itemselect 上的抽屉导航

android - 使用 SpeechRecognizer API 对 editText 进行语音输入的 Espresso 测试

android - 计算值-sw<n>dp int Android?

java - 在应用程序类的后台加载库