6

My Dependencies:

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'

I can´t find a way to simulate a click outside of an AlertDialog window to check something when it closes...

How can I do it?

Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162

2 Answers2

5

Check my answer.

Espresso can't do this.

You need to use uiautomator inside your Espresso test, add this to your project's gradle:

androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'

After your dialog appears, you can click on the screen at any coordinate:

UiDevice device = UiDevice.getInstance(getInstrumentation());
        device.click(x,y);

That will close your dialog

Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
2

You can do this in many cases by creating a custom 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);
}   

Then you can locate a known view in your dialog (say the 'OK' button) and invoke it as follows:

onView(withText("OK")).perform(clickXY(-200, 200));

Obviously, the x/y values that you use will be dependent upon your particular situation.

jdonmoyer
  • 1,245
  • 1
  • 18
  • 28
  • This yields `InjectEventSecurityException: Check if Espresso is clicking outside the app (system dialog, navigation bar if edge-to-edge is enabled, etc.).` in Espresso 3.5.1 – TWiStErRob Aug 27 '23 at 10:37