Permission Testing on Jetpack Compose
Asked Answered
D

1

8

I'm using Jetpack Compose for rendering the UI of my app. I'm currently developing some tests for a library, but I can't manage to find any proper ways to check for permissions. I'm currently using the Accompanist Permissions library to check for permissions. However, it seems like the permissions are already granted when the test starts, even though I'm currently checking for location permission, which should in fact not be granted, as far as I know.

How am I supposed to check whether or not the permissions are granted, and how to perform clicks on the permission dialog? Maybe with something like this?

composeTestRule.onNodeWithText("While using the app").performClick()

It seems quite dirty for me.

Note: I'm initializing composeTestRule just like the official guide shows:

@get:Rule
val composeTestRule = createComposeRule()

Thanks in advance for the help, and I'd be glad to provide more info if necessary.

Edit 1: It's important to remember to add the permission(s) to the manifest. In my case I'm using a sepparate module in my app for this library, so I had forgotten to add the permissions that I'm requesting. Example:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.yourpackage"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

</manifest>

Edit 2: Instructions such as

composeTestRule.onNodeWithText("Precise").performClick()
composeTestRule.onNodeWithText("While using the app").performClick()

totally don't work since the dialog is outside of the Compose View. Maybe using raw Espresso?

Final thoughts: After some intense investigation it seems that this may not be possible to be tested with Jetpack Compose testing, neither Espresso. This kind of tests must be performed with UiAutomator (official docs).

Demilune answered 20/5, 2022 at 9:29 Comment(1)
the same problem, the popup system hidden when I call request permission in UITest compose.Lemmuela
T
2

Just add this dependency

[versions]
testRules = "1.4.0"

[libraries]
androidx-rules = { group = "androidx.test", name = "rules", version.ref = "testRules" }

dependencies { androidTestImplementation(libs.androidx.rules) }

Then just add this at the beginning of your test class

@get:Rule
val permissionRule = GrantPermissionRule.grant(
    android.Manifest.permission.ACCESS_FINE_LOCATION,
    android.Manifest.permission.ACCESS_COARSE_LOCATION
)
Terrence answered 1/7 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.