我是Android开发的新手。我想使用Espresso来测试我的抽屉是否打开,然后点击一个项目并检查它是否会打开一个新活动。我一直在寻找关于这方面的例子,但没有运气。
答案 0 :(得分:29)
@Test
public void clickOnYourNavigationItem_ShowsYourScreen() {
// Open Drawer to click on navigation.
onView(withId(R.id.drawer_layout))
.check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be closed.
.perform(DrawerActions.open()); // Open Drawer
// Start the screen of your activity.
onView(withId(R.id.nav_view))
.perform(NavigationViewActions.navigateTo(R.id.your_navigation_menu_item));
// Check that you Activity was opened.
String expectedNoStatisticsText = InstrumentationRegistry.getTargetContext()
.getString(R.string.no_item_available);
onView(withId(R.id.no_statistics)).check(matches(withText(expectedNoStatisticsText)));
}
这正是您正在寻找的。 p>
答案 1 :(得分:1)
如果其他人遇到此问题并且他/她正在使用kotlin,则可以在ActivityScenario类上添加扩展功能以获取抽屉图标或后退按钮
有关更多说明,请检查此GOOGLE-TESTING-CODELAB-8
fun <T: Activity> ActivityScenario<T>.getToolbarNavigationContentDescriptor(): String {
var description = ""
onActivity {
description = it.findViewById<Toolbar>(R.id.toolbar).navigationContentDescription as String
}
return description
}
在测试中,您可以执行以下操作
// Check drawer is closed
onView(withId(R.id.drawer_layout)).check(matches(isClosed(Gravity.START)))
// Click drawer icon
onView(
withContentDescription(
scenario.getToolbarNavigationContentDescriptor()
)
).perform(click())
// Check if drawer is open
onView(withId(R.id.drawer_layout)).check(matches(isOpen(Gravity.START)))
编码愉快。 。