【问题标题】:PerformException Error Performing Single Click Works with 5dp marginPerformException 错误执行单击适用于 5dp 边距
【发布时间】:2019-10-19 05:48:43
【问题描述】:

我正在编写 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 留出边距,但如果没有边距,它就不起作用。我该如何解决?我的视图在布局中完全可见,只是它与最右边对齐。仅供参考,所有动画都已禁用

【问题讨论】:

    标签: android testing automated-tests android-espresso


    【解决方案1】:

    似乎坐标计算可能已被视图上的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());
    

    【讨论】:

    • 你是对的。当我删除 setRotation 时,它就起作用了。很高兴我能知道原因
    • 您能否分享有关您如何获得强制点击代码的详细信息?
    • @MayuriKhinvasara 我认为 Espresso 只为测试提供基本的视图操作,而且它们通常有局限性,但好消息是我们总是可以扩展类来进行更复杂的测试,尤其是使用自定义视图或奇怪的视图案例。它可能并不完美,但总要有所取舍。
    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多