PerformException Error Performing Single Click Works with 5dp 边距

PerformException Error Performing Single Click Works with 5dp margin

我正在编写 Instrumentation 测试,但无法单击我的视图。这是我的看法

<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/>

我的 constraintLayout 左右都有 30dp 的边距。我的测试用例如下 -

 @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())
}

它在 click() 上失败并收到错误 Error performing 'single click - At Coordinates: 1457, 1213 and precision: 16, 16' on view 'with id: com.test:id/go_to_next'.

如果我像 5dp 那样给我的 ImageView 留出边距,这会起作用,但如果没有边距,它就无法工作。我该如何解决?我的视图在布局中是完全可见的,只是它对齐到最右边。仅供参考,所有动画都已禁用

看来坐标计算可能已被视图上的 setRotation 调用 破坏 。您可以尝试物理旋转文件,或者创建自定义点击操作来强制点击它:

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();
        }
    };
}

然后在按钮或任何附加了 点击侦听器 的视图上使用它:

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