I have found the solution to this issue with a help from a suggestion on StackOverflow (the one i posted with the original post).
Instead of using "isAssignableFrom(AdapterView.class)" I use "isAssignableFrom(ListView.class)".
I then use a matcher to verify the context menu item count. And another matcher that checks the MenuItem at a certain position in the ListView and I can compare the IDs to make sure its the ID that I am expecting.
public boolean verifyRowContextMenuContents(String name, MyActionObject[] actions){
// invoke the row context menu
clickRowActionButton(name);
// The Context Menu Popup contains a ListView
int expectedItemCount = actions.length;
// first check the Popup's listView contains the correct number of items
onView(isAssignableFrom(ListView.class))
.check(matches(correctNumberOfItems(expectedItemCount)));
// now check the order and the IDs of each action in the menu is the expected action
for (int i = 0; i < expectedItemCount; i++) {
onView(isAssignableFrom(ListView.class))
.check(matches(correctMenuId(i, actions[i].getId())));
}
// close the context menu
pressBack();
return true;
}
private static Matcher<View> correctNumberOfItems(final int itemsCount) {
return new BoundedMatcher<View, ListView>(ListView.class) {
protected boolean matchesSafely(ListView listView) {
ListAdapter adapter = listView.getAdapter();
return adapter.getCount() == itemsCount;
}
};
}
private static Matcher<View> correctMenuId(final int position, final int expectedId) {
return new BoundedMatcher<View, ListView>(ListView.class) {
description.appendText("with position : " + position + " expecting id: " + expectedId);
}
@Override
protected boolean matchesSafely(ListView listView) {
ListAdapter adapter = listView.getAdapter();
Object obj = adapter.getItem(position);
if (obj instanceof MenuItem){
MenuItem menuItem = (MenuItem)obj;
return menuItem.getItemId() == expectedId;
}
return false;
}
};
}
With this code I can check the Context Menu contains the correct number of menu items, and that the items in the menu are the ones i am expecting (using ID verification) and the order I am expecting.