Search code examples
android-espressoandroid-12

Granting Bluetooth permissions in Espresso for Android 12


I work on a legacy project. This project uses Bluetooth Low Energy to connect with devices. Of course, I migrated the project to use the AndroidX libraries. Some time ago I started to write tests in Espresso because it was the only way to test the Ble interface, since the Android Emulator doesn't support the Bluetooth emulation.

The App was targeting Android 11 and was compatible with previous versions until Android 6.

Of course I had to grant the permissions with a JUnit4 rule to avoid the permission popup:

@Rule public GrantPermissionRule permissionRule = GrantPermissionRule.grant(android.Manifest.permission.ACCESS_FINE_LOCATION);

Two weeks ago my company decided to target Android 12. So I replaced the rule with:

@Rule public GrantPermissionRule permissionRule = GrantPermissionRule.grant(
        android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.BLUETOOTH_CONNECT);

Unfortunately, this rule doesn't grant the permissions for Android 12, the app rises the permission popup and all my test (that previously worked fine) break.

I also tried this in the function labeled as @Before:

InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
                "pm grant " + ApplicationProvider.getApplicationContext().getPackageName()
                        + " android.permission.BLUETOOTH_SCAN  android.permission.BLUETOOTH_CONNECT");

None of those solutions avoid the permission popup, so all our Bluetooth test brake.

Does anyone know how to grant the permissions for Espresso tests targeting Android 12?

thanks in advance.


Solution

  • After a while looking for a more elegant solution, the only way I can close the permission pop-up is to access to the acceptance button in one of these two ways:

    onView(withId(android.R.id.button1)).perform(click());
    

    or

    (withText(android.R.string.ok)).perform(click());
    

    It wasn't the solution I wanted but it works.