android - 如何使用 espresso 测试用例库单击工具栏中的菜单选项

标签 android unit-testing android-instrumentation

我想测试工具栏中的“设置”选项。单击“设置”选项时,它将启动新 Activity ,并从工具栏标题名称中我想确认它是否已成功启动。 下面是代码:- java代码

@RunWith(AndroidJUnit4.class)
@SmallTest
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mainActivityActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Before
    public void  intialize(){

    }

    @Test
    public void testCanGoToSettings() {
        onView(withId(R.id.toolbar))
                .perform(navigateTo(R.id.action_settings));
        String expectedNoStatisticsText = InstrumentationRegistry.getTargetContext()
                .getString(R.string.action_settings);
        onView(withId(R.id.toolbarSettings)).check(matches(withText(expectedNoStatisticsText)));

    }

}

xml代码

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/home_menu">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

我遇到以下错误。

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: com.xyz.android.control:id/toolbar

请帮忙,我该如何实现这个。

最佳答案

我相信这个答案是合适的 对于这个问题:[https://stackoverflow.com/a/36656925/2688351][1] .

在你的情况下,你应该写这样的东西:

// Click menu
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());

// Choose item "Settings"
onView(withText(mActivity.getString(R.string.action_settings))).perform(click());

// Check that settings activity was opened
onView(withText(mActivity.getString(R.string.some_settings_item))).check(matches(isDisplayed()));

关于android - 如何使用 espresso 测试用例库单击工具栏中的菜单选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179220/

相关文章:

android - 如何授予对 android 仪器测试的权限?

Android 使用mockito测试自定义 View

android - 仪器测试 : define a test as mandatory for the following

android - 将 edittext 的大小固定为与上面的微调器相同

android - Cordova/Ionic/PhoneGap 应用程序中可用的 CSS 和 Javascript 功能?

c# - 什么 block 没有被覆盖?

无返回类型函数的 Javascript 单元测试

android - InputMethodService 的仪器测试用例

android - 大疆Spark : missing support for FlightController. setMaxFlightHeight() FlightController.setMaxFlightRadius()

java - 找到应用程序崩溃的地方