如何使用espresso模拟Android上AlertDialog窗口之外的触摸

Dan*_*ico 5 testing android integration-testing android-espresso

我的依存关系:

androidTestCompile 'com.android.support.test:runner:0.3' 
androidTestCompile 'com.android.support.test:rules:0.3' 
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2' 
androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2') { 
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude module: 'recyclerview-v7' 
} 
androidTestCompile 'junit:junit:4.12'
Run Code Online (Sandbox Code Playgroud)

我无法找到一种方法来模拟AlertDialog窗口外部的单击以在关闭时检查某些内容...

我该怎么做?

小智 5

检查我的答案。

浓缩咖啡做不到这一点。

您需要在 Espresso 测试中使用uiautomator,将其添加到项目的 gradle 中:

androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
Run Code Online (Sandbox Code Playgroud)

对话框出现后,您可以单击屏幕上的任意坐标:

UiDevice device = UiDevice.getInstance(getInstrumentation());
        device.click(x,y);
Run Code Online (Sandbox Code Playgroud)

这将关闭您的对话框


jdo*_*yer 2

在许多情况下,您可以通过创建自定义 ClickAction 来完成此操作:

    public static ViewAction clickXY(final int x, final int y){
    return new GeneralClickAction(
            Tap.SINGLE,
            new CoordinatesProvider() {
                @Override
                public float[] calculateCoordinates(View view) {

                    final int[] screenPos = new int[2];
                    view.getLocationOnScreen(screenPos);

                    final float screenX = screenPos[0] + x;
                    final float screenY = screenPos[1] + y;
                    float[] coordinates = {screenX, screenY};

                    return coordinates;
                }
            },
            Press.FINGER);
}   
Run Code Online (Sandbox Code Playgroud)

然后,您可以在对话框中找到已知视图(说出“确定”按钮)并按如下方式调用它:

onView(withText("OK")).perform(clickXY(-200, 200));
Run Code Online (Sandbox Code Playgroud)

显然,您使用的 x/y 值将取决于您的具体情况。