How to click on Action Bar items when testing with Android Espresso?

Espresso has openActionBarOverflowOrOptionsMenu(Context context) method to open the action bar menu. You have to put it before your test action on the menu items.

import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;

@Test
public void testClickInsertItem() {
    openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().getTargetContext());
    onView(withId(R.id.action_insert)).perform(click());
}

Hope it can help someone with collaspingtoolbar

I have the following menu layout.

collasping Toolbar

enter image description here

After using Espresso Recorder, I discovered the menu button is click with withContentDescription function

enter image description here

I also used ToolBar and CollapsingToolbarLayout in the xml, what I did in the testing is just using the withContentDescription to open the menu.

menu.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">
  <item
    android:id="@+id/action_more"
    android:icon="@drawable/ic_more_vert_white_24dp"
    android:title="@string/menu_action_more"
    app:showAsAction="always">
    <menu>
      <item
        android:id="@+id/action_login"
        android:icon="@drawable/ic_account_circle_black_24dp"
        android:orderInCategory="100"
        android:title="@string/menu_login" />
      <item
        android:id="@+id/action_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:orderInCategory="100"
        android:title="@string/menu_settings" />
      <item
        android:id="@+id/action_about"
        android:icon="@drawable/ic_info_black_24dp"
        android:orderInCategory="100"
        android:title="@string/menu_about" />
    </menu>
  </item>
</menu>

MainTest.java

      @Test
      public void menu_Login() {        
        onView(withContentDescription(R.string.menu_action_more))
            .perform(click());
        onView(withText("Login")).perform(click());
        intended(hasComponent(LoginActivity.class.getName()));
      }