Android Marshmallow: Test permissions with Espresso?

前端 未结 13 1398
庸人自扰
庸人自扰 2020-11-29 19:31

The new permissions scheme introduced by Android Marshmallow requires checking for specific permissions at runtime, which implies the need to provide different flows dependi

13条回答
  •  生来不讨喜
    2020-11-29 20:20

    The accepted answer doesn't actually test the permissions dialog; it just bypasses it. So, if the permissions dialog fails for some reason, your test will give a false green. I encourage actually clicking the "give permissions" button to test the whole app behaviour.

    Have a look at this solution:

    public static void allowPermissionsIfNeeded(String permissionNeeded) {
        try { 
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasNeededPermission(permissionNeeded)) {
            sleep(PERMISSIONS_DIALOG_DELAY);
            UiDevice device = UiDevice.getInstance(getInstrumentation());
            UiObject allowPermissions = device.findObject(new UiSelector()
              .clickable(true) 
              .checkable(false) 
              .index(GRANT_BUTTON_INDEX));
            if (allowPermissions.exists()) {
              allowPermissions.click();
            } 
          } 
        } catch (UiObjectNotFoundException e) {
          System.out.println("There is no permissions dialog to interact with");
        } 
      } 
    

    Find the whole class here: https://gist.github.com/rocboronat/65b1187a9fca9eabfebb5121d818a3c4

    By the way, as this answer has been a popular one, we added PermissionGranter to Barista, our tool above Espresso and UiAutomator to make instrumental tests green: https://github.com/SchibstedSpain/Barista check it out, because we will maintain it release by release.

提交回复
热议问题