简体   繁体   中英

How to use robotium to check if an action bar menu item is present

I have some menu items in an ActionBar that are modified dynamically (for example, if the user logs in, I remove the 'login' menu item and replace it with a 'logout' item, etc).

So basically I'm trying to test this functionality using robotium and I figured I'd try to load a view and check if it is present or not, something like:

assertNull(solo.getView(R.id.action_login)); // action_login is an action bar menu item

But this approach isn't working since I'm getting the following error:

View with id: 'XXX' is not found!

Any idea how to test this kind of functionality? Thanks

The easiest way would be to make a helper method along the lines of:

public boolean viewExist(int id){
    try{
        solo.getView(id);
        return true;
    }catch(AssertionError e){
        return false;
    }
}

您可以调用菜单项并验证调用是否成功;

assertTrue(getInstrumentation().invokeMenuActionSync(activity, R.id.action_login, 0));

My approach that I've whipped up minutes ago is as following:

  1. Click on the overflow button itself (the three dots). To do that, find a view of type ActionMenuView. This can be done as following:

     assertTrue("Couldn't fetch overflow button", solo.waitForView(ActionMenuView.class, 1, 500)); ArrayList<ActionMenuView> actionMenuView = solo.getCurrentViews(ActionMenuView.class); assertFalse("Couldn't fetch overflow button", actionMenuView.isEmpty()); solo.clickOnView(actionMenuView.get(0)); 
  2. Waiting for the view with id equal to proper item id failed me. So what I did instead is I waited for item's string to appear.

     assertTrue("Action item not present", solo.waitForText( solo.getCurrentActivity().getString(R.string.my_action_string), 1, 500 ) ); 

As one may notice, this method has serious drawbacks - not only the uniqueness of action bar item string is required, but also clicking on the overflow might fail if there are other action bar buttons visible. Other than that, it works in my case - test implemented as above passes. However, if the line about clicking the overflow button is commented out, it fails (as expected).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM