如何使用espresso testcase库单击工具栏中的菜单选项

时间:2016-03-23 13:15:09

标签: android unit-testing android-instrumentation

我想测试"设置"工具栏中的选项。点击"设置"选项,它将启动新活动,并从工具栏标题名称我想确认它是否已成功启动。 以下是代码: - 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

请帮助,我如何实现这一点。

1 个答案:

答案 0 :(得分:3)

我相信这个答案是合适的 对于这个问题:[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()));