我有一个NavigationView
,其中有一个菜单,当用户未登录时,应禁用某些菜单项:
private void setupNavigationViewMenu(boolean isUserLoggedIn) {
Menu menu = mNavigationView.getMenu();
menu.findItem(R.id.item_charge_cards).setEnabled(isUserLoggedIn);
menu.findItem(R.id.item_charge_sessions).setEnabled(isUserLoggedIn);
menu.findItem(R.id.item_invoices).setEnabled(isUserLoggedIn);
}
我想创建一个Espresso测试,它会声明菜单项确实已被禁用。
我已经写了以下测试,但它失败了:
@Test
public void navigationMenuItems_AreDisabled() {
openNavigationDrawer();
onView(getNavigationItemWithString(R.string.navigation_view_item_charging_cards))
.check(matches(not(isEnabled())));
onView(getNavigationItemWithString(R.string.navigation_view_item_charging_sessions))
.check(matches(not(isEnabled())));
onView(getNavigationItemWithString(R.string.navigation_view_item_invoices))
.check(matches(not(isEnabled())));
}
public static Matcher<View> getNavigationItemWithString(String string) {
return allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
}
stacktrace:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'not is enabled' doesn't match the selected view.
Expected: not is enabled
Got: "AppCompatCheckedTextView{id=2131624121, res-name=design_menu_item_text, visibility=VISIBLE, width=651, height=126, 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=42.0, y=0.0, text=Laadpassen, input-type=0, ime-target=false, has-links=false, is-checked=false}"
...
您对如何编写正确的测试有任何建议吗?
答案 0 :(得分:1)
NavigationView
菜单项不是单个视图,而是ViewGroup,因此启用状态将应用于NavigationMenuItemView
,而不是AppCompatCheckedTextView
。要修复测试,必须使用以下匹配器在视图层次结构中查找正确的布局:
public static Matcher<View> getNavigationItemWithString(String string) {
Matcher<View> childMatcher = allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
return allOf(isAssignableFrom(NavigationMenuItemView.class), withChild(childMatcher));
}