PerformException Error Performing Single Click Works with 5dp margin

Viewed 4633

I am writing the Instrumentation test and i am unable to click my view. Here's my view

<ConstraintLayout......>
 <ImageView
        android:id="@+id/go_to_next"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:background="@drawable/rounded_bg"
        android:rotation="180"
        android:scaleType="centerInside"
        android:src="@drawable/ic_back"
        app:layout_constraintBottom_toBottomOf="@+id/mobile_number_edittext"
        app:layout_constraintEnd_toEndOf="parent" />
</ConstraintLayout/>

My constraintLayout has 30dp margin on both left and right. My Test case is following -

 @Test
fun useAppContext() {
    // Context of the app under test.
    val appContext = InstrumentationRegistry.getInstrumentation().targetContext
    assertEquals("com.test", appContext.packageName)
    onView(withId(R.id.go_to_next)).check(matches(isDisplayingAtLeast(90)))
    onView(withId(R.id.go_to_next)).perform(click())
}

It fails on click() and receives an error as Error performing 'single click - At Coordinates: 1457, 1213 and precision: 16, 16' on view 'with id: com.test:id/go_to_next'.

This works if I give margin to my ImageView like 5dp but it doesn't work without margin. How can I fix it? My View is completely visible in the layout, it's just it's aligned to the extreme right. FYI all animations are disabled

1 Answers

It seems the coordinates calculation may have been broken by setRotation call on the view. You could either try to rotate the file physically, or create a custom click action to force click on it instead:

public static ViewAction forceClick() {
    return new ViewAction() {
        @Override public Matcher<View> getConstraints() {
            return allOf(isClickable(), isEnabled(), isDisplayed());
        }

        @Override public String getDescription() {
            return "force click";
        }

        @Override public void perform(UiController uiController, View view) {
            view.performClick(); // perform click without checking view coordinates.
            uiController.loopMainThreadUntilIdle();
        }
    };
}

Then use it on a button or any view that has a click listener attached to it:

onView(withId(R.id.go_to_next)).perform(forceClick());
Related