我有这段代码
private void setupDrawerLayout() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
final int itemId = menuItem.getItemId();
switch (itemId) {
case R.id.drawer_my_mixes:
replaceFragment(MyMixesFragment.newInstance());
drawerLayout.closeDrawers();
break;
and so on...
我想制作espresso点击R.id.drawer_settings
,这将基本上打开一个名为SettingsFragment的片段。我该怎么做呢?我试过这个没有成功
private ViewInteraction navigateToSettings(){
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
return onView(withText("Settings")).perform(click());
}
答案 0 :(得分:4)
正确的方法是使用Espresso的onData功能。
onData(allOf(is(instanceOf(NavigationMenuItem.class)), ... )).perform(click());
但是NavigationMenuItem是不可访问的,因为它是一个私有的嵌套类。
问题正在等待https://code.google.com/p/android/issues/detail?id=187701找到解决方案。去添加星星; - )
答案 1 :(得分:1)
openActionBarOverflowOrOptionsMenu()无法打开NavigationView。
对我来说,以下工作:
//Open NavigationView
Matcher<View> isImageButton = withClassName(is(ImageButton.class.getName()));
Matcher<View> isInToolbar = isDescendantOfA(withId(R.id.toolbar));
onView(allOf(isInToolbar, isImageButton)).perform(click());
//Click on item in NavigationView
onView(withText(R.string.logout)).perform(click());
此解决方案暂时适用于我,直到用户40797建议的更好的解决方案正在运行...
答案 2 :(得分:0)
在您的程序包中:
public class NavigationViewTestHelper {
public static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
打开NavigationView后进行测试。
ViewInteraction navigationMenuItemView = onView(
allOf(childAtPosition(
allOf(withId(R.id.design_navigation_view),
childAtPosition(
withId(R.id.*your_navigation_view_id*),
0)),
1), // Position of the element in the Navigation view.
isDisplayed()));
navigationMenuItemView.perform(click());