I'm trying to test the permission request flow - if the proper screens and request dialogs are shown when user invokes some action requiring ungranted permission, but I can't make the request permission dialog appear in my tests, as inside the tests permissions are always granted, so this returns a permissionStatus == GRANTED and I need them to be denied.
val context: Context = InstrumentationRegistry.getInstrumentation().context
val permissionStatus = ContextCompat.checkSelfPermission(context, permissionNeeded)
Have anybody stumbled into this issue, or found another way of testing permission flows?
I've tried this also with espresso activityRule, without resetting to homepage etc, but no luck, so...
full - minimal
- code example is below:
@SdkSuppress(minSdkVersion = 23)
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
private lateinit var device: UiDevice
@After
fun tearDown() {
InstrumentationRegistry.getInstrumentation().uiAutomation
.executeShellCommand("pm grant com.example.odometer android.permission.ACCESS_COARSE_LOCATION")
}
@Before
fun startMainActivityFromHomeScreen() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
device.pressHome()
val launcherPackage: String = device.launcherPackageName
require(launcherPackage.isNotBlank())
device.wait(
Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT
)
val context = ApplicationProvider.getApplicationContext<Context>()
val intent = context.packageManager.getLaunchIntentForPackage(
BASIC_SAMPLE_PACKAGE
)?.apply {
// Clear out any previous instances
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
context.startActivity(intent)
// Wait for the app to appear
device.wait(
Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
LAUNCH_TIMEOUT
)
}
@Test
fun testPermissionDialog() {
val context: Context = InstrumentationRegistry.getInstrumentation().context
val permissionStatus =
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
assertNotEquals(PackageManager.PERMISSION_GRANTED, permissionStatus)
}
}
Edit: It happens also if the app is uninstalled before test.
Tested on emulator with API: 29 and 31_arm64
CodePudding user response: