4

I am developing an Android app using Kotlin. I am writing instrumented tests for my application. I am granting the permissions in my test using GrantPermissionRule as below.

@get:Rule 
var permissionRule: GrantPermissionRule = GrantPermissionRule.grant(android.Manifest.permission.ACCESS_FINE_LOCATION)

However, that does not fit well with my requirements. I am wiping out all the granted permissions after each does. Also, I like to test the scenarios where the permissions are not granted. I am launching the activity explicitly in my test like this.

@Test
fun exampleTest() {
    this.eventDetailsActivityRule.launchActivity(intent)
}

I like to explicitly grant the permissions using GrantPermissionRule after or before launching the activity. How can I do that?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • 1
    Another problem is that `GrantPermissionRule` indicates that granted permissions last for the duration of your instrumentation test ("Once a permission is granted it will apply for all tests running in the current Instrumentation. There is no way of revoking a permission after it was granted. Attempting to do so will crash the Instrumentation process."). This might force you to use the Android Test Orchestrator to have each test run in its own instrumentation, really slowing down your tests. – CommonsWare Dec 07 '19 at 21:17
  • 1
    But, assuming that you can live with that limitation, it appears as though the AndroidX `GrantPermissionRule` does not offer direct support for what you are seeking. You would need the `grantPermissions()` method to be `public`, so you can control when the permissions are granted. Unfortunately, at least in `androidx.test:rules:1.2.0`, it is `private`. – CommonsWare Dec 07 '19 at 21:19
  • "In androidx.test:rules:1.2.0, it is private" means there is no chance of solving this issue. I have to use the Android Test Orchestrator then. Thanks @CommonsWare – Wai Yan Hein Dec 07 '19 at 21:22
  • But how can I separate permissions using Android Test Orchestrator? Can you give me some links, please? – Wai Yan Hein Dec 07 '19 at 21:34
  • 1
    Sorry, I think that I may have confused you. `GrantPermissionRule`, as written, does not appear to allow you to grant permissions part-way through a test function. But, `GrantPermissionRule` is from a library, and you could always try forking it to create permission-granting code that you could use part-way through a test function. Assuming that you do that, you *also* would need to use Android Test Orchestrator, if you have 2+ tests that pertain to these permissions, so that permission grants in Test 1 do not affect Test 2. – CommonsWare Dec 07 '19 at 21:38

0 Answers0