如何检查在Espresso UI自动化测试中启用/禁用MenuItem

sJy*_*sJy 6 android menuitem android-espresso

我正在Espresso for Android中编写UI自动化测试,并且遇到了迄今为​​止我还没有任何解决方案的场景.

在一个Fragment,我有OptionsMenu一个项目.其状态MenuItem根据API响应的值设置.

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.clear();
    getActivity().getMenuInflater().inflate(R.menu.menu_cancel_order, menu);
    MenuItem cancelMenuItem = menu.findItem(R.id.cancel_order);
    if(something) { // something can be a boolean value from server
        cancelMenuItem.setEnabled(true);
    } else {
        cancelMenuItem.setEnabled(false);
    } 
}
Run Code Online (Sandbox Code Playgroud)

对于UI测试,我需要编写测试用例来检查是否MenuItem启用/禁用.

点击overflowmenu,

ViewInteraction actionMenuItemView = onView(
            allOf(withId(R.id.action_settings), withContentDescription("Settings"), isDisplayed()));
actionMenuItemView.perform(click());
Run Code Online (Sandbox Code Playgroud)

到目前为止,我试图检查断言的内容如下.

onView(allOf(withText("Cancel Order"), withId(R.id.cancel_order))).check(matches(not(isEnabled())));
Run Code Online (Sandbox Code Playgroud)

但这会引发NoMatchingViewException消息

NoMatchingViewException:层次结构中找不到匹配的视图:(带有text:是"Cancel Order",ID为:com.equinix.ecp.betatest:id/cancel_order)

所以我尝试将其更改为

onView(allOf(withText("Cancel Order"))).check(matches(not(isEnabled())));
Run Code Online (Sandbox Code Playgroud)

不知何故,这与视图匹配,但它不是MenuItem,而是MenuItem中的TextView,因为我设置setEnabled()为MenuItem,check()Assertion将不会按预期工作,因为它是一个TextView.

所以我的问题是如何编写Test以检查MenuItem的启用/禁用状态.

sta*_*uel 0

我建议您使用菜单项的 ID 来执行检查。我用这个菜单尝试过:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="at.hellobank.hellomarkets.symbols.DetailActivity">

<item
    android:id="@+id/action_1"
    android:icon="@android:drawable/arrow_down_float"
    android:title="Menu1"
    app:showAsAction="always" />

<item
    android:id="@+id/action_2"
    android:enabled="false"
    android:icon="@android:drawable/arrow_down_float"
    android:title="Menu2"
    app:showAsAction="always" />
</menu>
Run Code Online (Sandbox Code Playgroud)

因此,一项菜单项被启用,一项被禁用。我的测试看起来像这样并且按预期工作:

@Test
public void testMenuItemsStatus() throws Exception {
    onView(withId(R.id.action_1)).check(matches(isEnabled()));
    onView(withId(R.id.action_2)).check(matches(not(isEnabled())));
}
Run Code Online (Sandbox Code Playgroud)

一般来说,在测试中使用 ID 更好,恕我直言,因为你更独立于拼写错误和通用语言。withText("Cancel Order")如果您测试以其他语言本地化的应用程序,则可能无法正常工作。