Search code examples
androidandroid-permissionsandroid-espresso

Unable to test code requiring CHANGE_NETWORK_STATE / WRITE_SETTINGS permission on Marshmallow


I am trying to upgrade my app's targetSDK to above 23 and I've run into a small problem. I have an activity that binds traffic to Wifi (to measure the network speed to the router, even if the router is not connected to the internet). In order for that to happen my app needs the CHANGE_NETWORK_STATE permission. That permission is usually granted directly if declared in the manifest. On Android 6.0 (exact, this was fixed in 6.0.1 IIRC) CHANGE_NETWORK_STATE is broken and won't be granted so you need the WRITE_SETTINGS permission instead. I've implemented a way for Android 6.0 Users to grant that permission but when I want to test my Activity using espresso I am unable to do so. Permissions are granted to tests by adding something like

@Rule public GrantPermissionRule runtimePermissionRule = GrantPermissionRule.grant(Manifest.permission.CHANGE_NETWORK_STATE);

to the TestCase. That worked in other places in the app but for this I get junit.framework.AssertionFailedError: Failed to grant permissions, see logcat for details in my test results. In logcat I find E/GrantPermissionCallable: Permission: android.permission.WRITE_SETTINGS cannot be granted! or the same with CHANGE_NETWORK_STATE, I've tried granting both and they both don't work. Is there any other way for me to grant the permission in the testing environment? Or am I unable to test this activity on 6.0 devices from now on?


Solution

  • Because WRITE_SETTINGS is a sensitive permission, you won't be able to grant it using GrantPermissionRule in API 23. You will likely end up needing to use UIAutomator in your tests to select the appropriate response in the permissions management screen.