AdamMc331
AdamMc331

Reputation: 16690

How to click contextual action bar item using Espresso framework

I am writing a test case that long clicks an item in my ListView (backed by a CursorAdapter) which will pull up a Contextual Action Bar and has a menu item that allows the user to delete that item.

I use the following code:

public void testDeleteFirstAccount(){
    // Long click
    onData(is(instanceOf(Cursor.class))).atPosition(0).perform(longClick());

    // Click delete menu item
    onView(withId(R.id.action_delete_account)).perform(click());

    // Find alert button with text
    onView(withText("Yes")).perform(click());
}

However, I am unable to click the button because I believe the test is running too quickly. I get the following error:

android.support.test.espresso.PerformException: Error performing 'single click' on view 'with id: com.example.android.cashcaretaker:id/action_delete_account'.

Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: at least 90 percent of the view's area is displayed to the user.

The reason I believe the test is too quick is because if I add Thread.sleep() after the long click, everything will work fine. I only did this as a test to verify my suspicions, I'm not sure stopping the UI like that is the proper way to move forward.

I have also tried adding getInstrumentation().waitForIdleSync() but had no success.

Am I doing something else wrong? What is the proper way to use Espresso to click a CAB item?

Upvotes: 1

Views: 1099

Answers (1)

Daniel
Daniel

Reputation: 869

Perhaps the view is still being animated at the moment that Espresso tries to click the ContextualActionBar item. And if you set a timeout, the animation has time to finish and the view is completely displayed by the time the click is performed.

Have you tried disabling animations in the test device as stated in the Espresso Setup guide?

Upvotes: 4

Related Questions